Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 使用实体框架更新模型中列表属性的最佳方法是什么?_Asp.net Mvc_Entity Framework_Model View Controller - Fatal编程技术网

Asp.net mvc 使用实体框架更新模型中列表属性的最佳方法是什么?

Asp.net mvc 使用实体框架更新模型中列表属性的最佳方法是什么?,asp.net-mvc,entity-framework,model-view-controller,Asp.net Mvc,Entity Framework,Model View Controller,我的模型如下所示: public class Parent { public int Id {get; set;} public virtual List<Child> Children {get; set;} } public class Child { public int Id {get; set;} public int age {get; set;} } 您能在更新完成的地方添加控制器代码吗?@dellywheel添加了控制器代码。thx控制器代码看起来

我的模型如下所示:

public class Parent
{
  public int Id {get; set;}
  public virtual List<Child> Children {get; set;}
}

public class Child
{
  public int Id {get; set;}
  public int age {get; set;}
}

您能在更新完成的地方添加控制器代码吗?@dellywheel添加了控制器代码。thx控制器代码看起来正常。我会在
db.SaveChanges()周围放置一个try catch
并查找
DbUpdateException
    public ActionResult Edit(ViewModel model, String[] selectedChildren)
    {
        var parent= db.Parent.FirstOrDefault(r => r.Id== model.Parent.Id);

        //Delete any child from parent that is not in selected children  
        foreach (var child in selectedChildren)
        {
            if (!(Parent.Children.Contains(child)))
            {
                parent.Children.Remove(child);
            }
        }

        foreach (var s in selectedChildren)
        {
            var child = db.Children
                .FirstOrDefault(p => p.Id == s);
            parent.Children.Add(child);
        }

        if (ModelState.IsValid)
        {
            db.Entry(parent).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(model);
    }