实体框架4 - 删除对象

时间:2011-02-18 09:15:23

标签: c# asp.net entity-framework entity-framework-4

我的DataBase中有3个表

CmsMasterPages
CmsMasterPagesAdvSlots (Pure Juction Table)
CmsAdvSlots

这是我的EDM图片:

enter image description here

我需要找出与CmsMasterPage连接的所有对象CmsAdvSlot(它在我的代码中发布了belove), 和删除数据库中的结果(CmsAdvSlot)。

当我找到主题时,我的问题是我无法删除此对象

Error: The object cannot be deleted because it was not found in the ObjectStateManager. 

        int findMasterPageId = Convert.ToInt32(uxMasterPagesListSelector.SelectedValue);
        CmsMasterPage myMasterPage = context.CmsMasterPages.FirstOrDefault(x => x.MasterPageId == findMasterPageId);
        var resultAdvSlots = myMasterPage.CmsAdvSlots;
        // It is working until here
        foreach (var toDeleteAdv in resultAdvSlots)
        {
            context.DeleteObject(myMasterPage.CmsAdvSlots.Any()); // ERORR HERE!!
            context.SaveChanges();
        }

知道怎么解决吗?谢谢你的时间! : - )

3 个答案:

答案 0 :(得分:5)

试试这个:

while (myMasterPage.CmsAdvSlots.Count > 0)
{
  var slot = myMasterPage.CmsAdvSlots.First();
  myMasterPage.CmsAdvSlots.Remove(slot); // This is required only in some scenarios - it depends on type of entities you are using.
  context.DeleteObject(slot);
}

context.SaveChanges();

答案 1 :(得分:0)

.Any()返回一个布尔值。请改用.First().First()将在您的情况下返回第一个CmsAdvSlot

如果你想删除所有CmsAdvSlot,我会关注@Ladislav Mrnka的例子。

答案 2 :(得分:0)

context.DeleteObject(myMasterPage.CmsAdvSlots.Any());myMasterPage.CmsAdvSlots.Any()应该给你一个布尔 您应该尝试使用myMasterPage.CmsAdvSlots.First()代替!