如何在单个方法中使用Entity Framework删除,添加和更新

时间:2016-12-08 12:40:53

标签: c# entity-framework linq-to-sql

我的一个功能中有Parent-Children结构。我正在使用EF6。

我能够成功添加/更新子记录,但是想要从已从UI中删除的db中删除一些子记录。以下是我到目前为止所尝试的内容..

using (dbBlinkContext dbContext = new dbBlinkContext())
{
    // Add/Update Parent
    if (entity.parentID <= 0)
        dbContext.Entry(entity).State = System.Data.Entity.EntityState.Added;
    else
        dbContext.Entry(entity).State = System.Data.Entity.EntityState.Modified;

    // Here I want to remove Children that got deleted from UI
    var dbChildren = dbContext.Children.Where(x => x.ParentID == entity.ParentID).ToList();     
    // this code is not working
    dbChildren.RemoveAll(c => !entity.Children.Contains(c)) // breaks here saying dbChildren not part of entity...

    // Add/Update Children
    if (entity.Children.IsNotNull() && entity.Children.Count > 0)
    {
        foreach (ChildType child in entity.Children)
        {
            if (Child.ChildID <= 0)
                dbContext.Entry(Children).State = System.Data.Entity.EntityState.Added;
            else
                dbContext.Entry(Children).State = System.Data.Entity.EntityState.Modified;
        }
   }

  dbContext.SaveChanges();
 }

1 个答案:

答案 0 :(得分:0)

您正尝试从列表中删除子项,但您需要从entity.Children中删除它们,或者从dbContext.Children中删除它们。

假设entity.Children不为null并且包含您要保留的子项,而不是“dbChildren.RemoveAll(c =&gt;!entity.Children.Contains(c))”,请尝试:

dbContext.Children.RemoveRange(dbChildren.Except(entity.Children));