简体   繁体   中英

Force Entity Framework to recognise a TPT Inheritance Structure

Given an example structure as below, Entity Framework doesn't recognise the base Entity inheritance, and thus doesn't map it as a TPT Inheritance between User and Entity.

// Where DbSet<User> Users { get; set; } is used
public class User : User<int> { }

public class User<TTest> : Entity {
    public TTest Whatever { get; set; }
}

public abstract class Entity {
    public int EntityId { get; set; }
}

I believe this is because EF will only look at the first level inheritance structure and never see the Entity as the base class, just that it has its properties.

So my question is, how can I force EF to recognise that Entity is indeed the base class? Just defining that User has a ForeignKey to Entity in the migration obviously isn't enough, as it still doesn't create that underlying row.


Bonus points: I've already noted that I can't go another level down (ie. Employee : User ), but if you'd like to correct me on that I'll be forever in your debt also.


Update : Repro available here on github.com .

Update2: Gert Arnold's theory about not being able to map generic classes and thus breaking the chain unfortunately generated the same migration wherein User didn't fall through to Entity .

Update3: I can confirm that the stricken out "bonus" above does indeed work, when User maps correctly. The inheritance structure of Entity : User : Employee works when all 3 are tables, it is obviously not working when User can't even map back to Entity, which I believe now to be a bug in EF.

You need to add a DbSet for each type that you want EntityFramework to add a table for, like this:

public virtual DbSet<Entity> Entities { get; set; }
public virtual DbSet<User> Users { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM