实体框架中的级联更新

本文关键字:级联 更新 框架 实体 | 更新日期: 2023-09-27 17:58:36

我有以下涉及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 Children以及DbSet Parents,我想进行以下更新操作:

//.. 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集合(或所有虚拟集合等)中的对象进行迭代,并调用上下文。Set()。AddOrUpdate(childModified)。我希望此行为在更新父级时是自动的。

有办法做到这一点吗?

谢谢,Ionut

实体框架中的级联更新

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

但我知道hibernate有它。

但是,您可以在ApplicationDbContext类中执行类似于覆盖方法savechanges()的操作类似于这里提到的级联删除

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();
                  }
   }

我想这就是你想要的,我还没有测试过这个