【问题标题】:Conditional mapping with graphdiff使用 graphdiff 进行条件映射
【发布时间】:2015-12-05 04:59:29
【问题描述】:

我的DbContext 中有以下实体:

public class A
{
   public A()
   {
       Bs = new List<B>(); 
   }

   public ICollection<B> Bs { set; get; }
}   

有时我想更新a 图表:

var a = dbContext.As
       .AsNoTracking()
       .Include(x=>x.Bs)
       .firstOrDefault();

var c = new C();
a.Bs.Add(c);

var d = new D();
var e1 = new E();
var e2 = new E();
d.Es.Add(e1); //<-- added new E
d.Es.Add(e2); //<-- added new E

a.Bs.Add(d);

我想用Bs更新a(也更新C,D,E)使用graphdiff

dbContext.UpdateGraph(a,map=>map.OwnedCollection(x=>x.Bs));

这会更新 ABs、Cs、Ds,但不会更新 Es。

所以我想,我需要为graphdiff 定义一个条件映射,以更新Es,类似于:

dbContext.UpdateGraph(a,map=>map.OwnedCollection(x=>x.Bs.OfType<D>(), 
                                             with =>with.OwnedCollection(t=>t.Es))
                                .OwnedCollection(x=>x.Bs.OfType<C>()));

有什么方法可以完成这项工作吗?

【问题讨论】:

  • 在 dbContext 中你有没有说过 d '拥有'集合 Es ?类似 dbContext.UpdateGraph(d,map=>map.OwnedCollection(x=>x.Es)); ?

标签: c# entity-framework ef-code-first graphdiff


【解决方案1】:

我认为使用您当前的班级结构是不可能的。但是,我找到了一种方法来实现这一点,但是您必须对代码进行一些更改。

更新A

public class A
{
   public A()
   {
       Cs = new List<C>(); 
       Ds = new List<D>(); 
   }

   //PK
   public int AId { get; set; }

   public ICollection<C> Cs { set; get; }
   public ICollection<D> Ds { set; get; }       
} 

更新BCD

public class B
{
    public int BId { get; set; }
}

public class C : B
{
    //FK that links C to A
    public int FK_C_AId { get; set; }
}

public class D : B
{
    //FK that links D to A
    public int FK_D_AId { get; set; }

    public ICollection<E> Es { get; set; }

    public D()
    {
        Es = new List<E>();
    }
}

为了维护 TPH 策略,一些映射是必要的。

modelBuilder.Entity<A>()
    .HasMany(i => i.Cs)
    .WithRequired()
    .HasForeignKey(i => i.FK_C_AId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<A>()
    .HasMany(i => i.Ds)
    .WithRequired()
    .HasForeignKey(i => i.FK_D_AId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<B>()
    .Map<C>(m => m.Requires("Discriminator").HasValue("C"))
    .Map<D>(m => m.Requires("Discriminator").HasValue("D"));

现在,您拥有几乎相同的数据库结构。 CD 仍然映射到同一个表。

最后,更新图表:

context.UpdateGraph(a, map => map
    .OwnedCollection(b => b.Cs)
    .OwnedCollection(b => b.Ds, with => with
        .AssociatedCollection(e => e.Es)));

希望对你有帮助!

【讨论】:

    【解决方案2】:

    您可以将其与 graphdiff 一起使用:

    dbContext.UpdateGraph(a, map => map
        .OwnedCollection(b => p.Bs, with => with
        .AssociatedCollection(p => p.Es)));
    

    查看此链接: GraphDiff Explanation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-20
      相关资源
      最近更新 更多