简体   繁体   English

实体框架4-删除对象

[英]Entity Framework 4 - Delete Object

I have 3 Tables in my DataBase 我的数据库中有3个表

CmsMasterPages
CmsMasterPagesAdvSlots (Pure Juction Table)
CmsAdvSlots

Here a Picture of my EDM: 这是我的EDM图片:

在此处输入图片说明

I need find out all objects CmsAdvSlot connected with a CmsMasterPage (it is working in my code posted belove), and DELETE the result (CmsAdvSlot) from the DataBase. 我需要找出所有与CmsMasterPage连接的对象CmsAdvSlot(它在我的代码发布后才起作用),然后从数据库中删除结果(CmsAdvSlot)。

My Problem is I am not able to DELETE this Objects when I found theme. 我的问题是找到主题后我无法删除该对象

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();
        }

Any idea how to solve it? 知道如何解决吗? Thanks for your time! 谢谢你的时间! :-) :-)

Try this: 尝试这个:

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();

.Any() returns a boolean. .Any()返回一个布尔值。 Use .First() instead, .First() will in your case return the first CmsAdvSlot . 使用.First()代替, .First()在您的情况下将返回第一个CmsAdvSlot

If you want to remove all CmsAdvSlot I would follow @Ladislav Mrnka's example. 如果要删除所有CmsAdvSlot ,请遵循@Ladislav Mrnka的示例。

In context.DeleteObject(myMasterPage.CmsAdvSlots.Any()); context.DeleteObject(myMasterPage.CmsAdvSlots.Any());
myMasterPage.CmsAdvSlots.Any() should return you a bool You should try using myMasterPage.CmsAdvSlots.First() instead! myMasterPage.CmsAdvSlots.Any()应该返回布尔值,您应该尝试使用myMasterPage.CmsAdvSlots.First()代替!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM