实体框架中的级联更新

时间:2014-04-15 13:20:48

标签: c# sql sql-server entity-framework sql-update

我有以下场景涉及2个类:

public class Parent
{
  [Key]
  public int Id {get;set;}

   //.. Other properties here

  public virtual IList<Child> Children {get;set;} 
}

public class Child
{
  [Key]
  public int Id {get;set;}
  public int ParentId {get;set;}

   //.. Other properties here

  [ForeignKey("ParentId")]
  public virtual Parent {get;set;} 
}

我还有 DbContext 以及相关的 DbSet儿童 DbSet父母,我想进行以下更新操作:

//.. Get some Parent instance -> convert it to ParentVM -> do some operations on ParentVM in the Service //layer () -> then try to update it back using EF: 
// parentVM now contains a modified version both in the primitive properties and also in the children  collection: some children have new values  


var parent = ConvertBackToORMModel(parentVM); //converts everything back, including the Children collection

using (var context = new ApplicationDbContext())
{
  context.Set<Parent>().AddOrUpdate(parent);
  //context.Set<Child>().AddOrUpdate(childModified); // If I do this here, it saves also the modified children back in the DB; but I want this to be **automatic when updating the parent**

  context.SaveChanges(); //here, the primitive modified properties are saved in DB, the modified children collection remains the same
} 

问题在于,上面的代码片段是通用的,这意味着我需要迭代,具体取决于通过Children集合(或所有虚拟集合等)的对象,并调用 context.Set( ).AddOrUpdate(childModified); 表示每一个。我希望在更新父级时自动执行此操作。

有没有办法做到这一点?

谢谢, Ionut

1 个答案:

答案 0 :(得分:2)

我认为实体框架没有级联更新功能,

但我知道hibernate有它。

然而,您可以在ApplicationDbContext类中执行类似覆盖方法savechanges()的操作 类似于提及here

的级联删除
ApplicationDbContext : DbContext
    {
               public override int SaveChanges()
                  {
                  //sets child in ram memory  entity state to modified 
                  //if its parent entity state is modified each time you call SaveChanges()
                  Child.Local.Where(r => Entry(r.Parent).State == EntityState.Modified)
                 .ToList().ForEach(r => Entry(r).State=EntityState.Modified);

                  base.SaveChanges();
                  }
   }

我认为这就是你要找的,我没有测试过这个