Quantcast
Channel: entityframework Discussions Rss Feed
Viewing all articles
Browse latest Browse all 1793

New Post: Mapping to abstract class TPH can't use single FK for derived class

$
0
0
@andreabelloni I don't think that EF supports the mapping that you are trying to make. One problem is that the same navigation property, defined on A, is being used for two different relationships: B -> D, and C -> D. You could get the table structure similar to what you want if you are willing to have a single relationship from A to D. This will mean that D has only one collection that will contain both B and C instances. The following code sets up such a mapping:
public abstract class A
{
    public int ID { get; set; }
    public string Code { get; set; }
    public int IdExt { get; set; }

    public virtual D D { get; set; }
}

public class B : A { }
public class C : A { }
public class D
{
    public int ID { get; set; }
    public virtual ICollection<A> ASet { get; set; }
}

public class SomeContext : DbContext
{
    public DbSet<B> BSet { get; set; }
    public DbSet<C> CSet { get; set; }
    public DbSet<D> DSet { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<A>()
            .ToTable("A");

        modelBuilder
            .Entity<A>()
            .Map<B>(t => t.Requires("Type").HasValue("B").IsRequired())
            .Map<C>(t => t.Requires("Type").HasValue("C").IsRequired());

        modelBuilder
            .Entity<A>()
            .HasRequired(t => t.D)
            .WithMany(t => t.ASet)
            .HasForeignKey(t => t.IdExt);
    }
}
This results in an A table that looks like this:
  • ID: PK
  • Code
  • IdExt: FK
  • Type: Discriminator
This table structure doesn't have a D_ID column. If you need that column can you provide some info as to what it is for? It would be created and used as the FK for the relationship exception that in the Code First configuration the IdExt column is made the FK meaning that D_ID isn't used anymore.

Thanks,
Arthur

Viewing all articles
Browse latest Browse all 1793

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>