Cascade Update in Entity Framework

2019-08-08 09:44发布

问题:

I have the following scenario involving 2 classes:

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

   //.. Other properties here

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

and

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

   //.. Other properties here

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

I also have an DbContext with the associated DbSet Children and DbSet Parents and I want to make the following update operation:

//.. 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
} 

The problem is that, the above code snippet is generic, which means that I would need to iterate, depending on the object through the Children collection (or all virtual collections, etc.) and call context.Set().AddOrUpdate(childModified); for each one. I want this behavior to be automatic when updating the parent.

Is there any way to do this?

Thanks, Ionut

回答1:

I believe entity framework does not have cascade update feature,

but I know hibernate has it.

however you could do something like overwritething method savechanges() in ApplicationDbContext class similar to cascade delete mentioned 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();
                  }
   }

I think this is what you are looking for, I have not tested this