c# – How to make TPT approach through Fluent API while inheriting from generic class?

Question:

I will describe the essence. There are several service types ( Service.cs , ServiceMeetGuest.cs ) and a ticket type ( Bid.cs , BidMeetGuest.cs ). With migrations in service types, everything is simple.

But the types of requests are inherited from the generic class, the type of TService specified in the generic type TService . Tried doing it this way, there is a generic class:

public class BidBase<TService>
{
    public long Id { get; set; }

    ...

    [ForeignKey("Service")]
    [Required]
    public long ServiceId { get; set; }
    public virtual TService Service { get; set; }
}

And declaring the entity in ApplicationDbContext :

public DbSet<BidBase<Service>> Bids { get; set; }
public DbSet<BidBase<ServiceMeetGuest>> BidsMeetGuest { get; set; }

As it turns out, Entity Framework does not support generic types. So I decided to add classes:

public class Bid : BidBase<Service> { }
public class BidMeetGuest : BidBase<ServiceMeetGuest> {}

And DbSet :

public DbSet<Bid> Bids { get; set; }
public DbSet<BidMeetGuest> BidsMeetGuest { get; set; }

Everything is ok, but there is no connection between them, Entity Framework perceives them as 2 different entities, although they are inherited from BaseBid.cs . How do I do Table Per Type approach in between ( https://metanit.com/sharp/entityframework/7.2.php ) via Fluent Api?

Answer:

modelBuilder.Entity<Bid>().ToTable("BidBase");
modelBuilder.Entity<BidMeetGuest>().ToTable("BidBase");
Scroll to Top