我有以下涉及 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 集合(或所有虚拟集合等)进行迭代,并调用 context.Set( ).AddOrUpdate(childModified); 每一个。我希望在更新父级时自动执行此行为。
有什么办法吗?
谢谢, 爱诺特
最佳答案
我相信 Entity Framework 没有级联更新功能,
但我知道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();
}
}
我想这就是你要找的,我还没有测试过
关于c# - Entity Framework 中的级联更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23084986/