c# - Entity Framework 中的级联更新

标签 c# sql sql-server entity-framework sql-update

我有以下涉及 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 ChildrenDbSet 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/

相关文章:

c# - 传入对象作为输出参数

c# - 如何在 ASP.NET Web API 中使用缓存?

sql - [ColumnName] 的 DB2 等效项

sql-server - 内存优化数据库和表变量

sql-server - 多个 Include/ThenInclude 在 EF Core 中导致重复

c# - Windows 窗体中通用事件处理程序的解决方法

c# - 正在分发 dll : What to do with . lib 文件吗?

java - 当两个不相关的表都有复合主键时,Hibernate 连接两个表

mysql - 棘手的 SQL 连接查询

sql - 使用可选条件/或连接表