Conditional mapping with graphdiff

别等时光非礼了梦想. 提交于 2019-12-04 22:13:59

You can use this with graphdiff:

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

see this link: GraphDiff Explanation

I don't believe that is possible using your current class structure. However, I found a way to accomplish this, but you have to make some changes in your code.

Update the 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; }       
} 

Update B, C, and D:

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>();
    }
}

In order to maintain the TPH strategy, some mappings are necessary.

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"));

Now, you have almost the same database structure. C and D are still mapped to the same table.

Finally, update the Graph:

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

Hope it helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!