我有以下涉及 2 个类的场景:
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;}
}
我也有一个数据库上下文与相关的数据库集子级 and 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
}
问题是,上面的代码片段是通用的,这意味着我需要根据子集合(或所有虚拟集合等)中的对象进行迭代并调用context.Set().AddOrUpdate(childModified);为每一个。我希望在更新父级时自动执行此行为。
有什么办法可以做到这一点吗?
谢谢,
约努特
我相信实体框架没有级联更新功能,
但我知道休眠 http://hibernate.org/ has it.
但是您可以在 ApplicationDbContext 类中执行类似覆盖方法 savechanges() 的操作
类似于提到的级联删除here http://blog.oneunicorn.com/2012/06/02/deleting-orphans-with-entity-framework/
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();
}
}
我想这就是你正在寻找的,我还没有测试过这个
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)