【问题标题】:ASP.NET Entity Framework - updating child dependencies with AttachASP.NET Entity Framework - 使用 Attach 更新子依赖项
【发布时间】:2016-08-18 18:16:34
【问题描述】:

关于实体框架的问题 - 我正在寻找更新父子记录的更有效方法。

场景 - 我们有一个包含一个或多个子对象的父对象。当父对象更新时,我们需要清除所有当前的子记录并重新添加新的子记录。

例如:

public bool UpdateProfile(Parent record)
{
        try
        {
            _context.Parent.Attach(record);       
            _context.Entry(record).State = EntityState.Modified;

            List<Child> childrenToDelete = GetChildrenByParentId(parent.Id);
            foreach (Child child in childrenToDelete)
            {
                _context.Child.Remove(child);
                _context.Entry(child).State = EntityState.Deleted;
            }
            foreach (Child child in record.children)
            {
                _context.ProfileCategories.Add(child);
            }
            _context.SaveChanges();
            return true;
}
        ...
    }

上面的代码在“_context.Parent.Attach(record)”行抛出了一个异常,表明存在重复的记录 ID。所以我们的解决方法是:

public bool UpdateProfile(Parent record)
{
    try
    {
        var originalChildren = record.children;
        record.children = new List<Child>();
        _context.Parent.Attach(record);       
        _context.Entry(record).State = EntityState.Modified;
        _context.SaveChanges();

        List<Child> childrenToDelete = GetChildrenByParentId(parent.Id);
        foreach (Child child in childrenToDelete)
        {
            _context.Child.Remove(child);
            _context.Entry(child).State = EntityState.Deleted;
        }
        foreach (Child child in originalChildren)
        {
            _context.ProfileCategories.Add(child);
        }
        _context.SaveChanges();
        return true;
   }
   ...
}

第二段代码有效,但我觉得它并不理想。

谁能告诉我们为什么 Attach 会抛出重复的 Id 异常以及我们拥有的解决方案是否是处理此问题的最佳方法?

【问题讨论】:

    标签: asp.net entity-framework entity-framework-6


    【解决方案1】:

    未经测试,但我会拍摄这样的东西:

        public void UpdateProfile(Parent record)
        {
            using(var db = new MyContext())
            {
                var children = db.Children.Where(x => x.ParentId == record.Id);
                db.ProfileCategories.AddRange(children);
                db.Children.RemoveRange(children);
                db.SaveChanges();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2017-04-22
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      相关资源
      最近更新 更多