实体框架中的级联更新 [英] Cascade Update in Entity Framework
问题描述
我有以下两种情况:
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家长,我想进行以下更新操作:
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
}
问题是,上面的代码片段是通用的,这意味着我需要迭代,取决于通过Children集合(或所有虚拟集合等)的对象,并调用 context.Set ().AddOrUpdate(childModified); 。更新父母时,我希望这个行为是自动的。
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.
有没有办法呢?
谢谢,
Ionut
Thanks, Ionut
推荐答案
我相信实体框架没有级联更新功能,
I believe entity framework does not have cascade update feature,
但我知道 hibernate 有它。
但是你可以在ApplicationDbContext类
中做一些覆盖方法savechanges(),类似于提到的级联删除 here
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
这篇关于实体框架中的级联更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!