开发者

Entity Framework Code First TPH Inheritance with Generic Repository

开发者 https://www.devze.com 2023-04-10 13:12 出处:网络
I\'m probably misunderstanding code-first table-per-hierarchy inheritance, but this is my set-up: I have HTMLGadgets (and other types) inheriting from Gadget, which inherits from Entity. Entity has on

I'm probably misunderstanding code-first table-per-hierarchy inheritance, but this is my set-up: I have HTMLGadgets (and other types) inheriting from Gadget, which inherits from Entity. Entity has one property, Id, so I can use it in a generic repository, à la this tutorial.

public abstract class Entity {
    [Key]
    public int Id { g开发者_如何转开发et; set; }
}   

public abstract class Gadget : Entity {       
    public string Content { get; set; }
}

public class HTMLGadget : Gadget
{
    public string SomeProperty { get; set;}
}

To implement TPH inheritance I have this in my context:

public DbSet<Gadget> Gadgets { get; set; }

So, I want everything to use the base Id, so everything is an Entity. But how do I get that to participate in code first inheritance? I can see the problem: if I change the context to have

public DbSet<Entity> Entities{ get; set; }

it might work, but I'd have everything (there will be more tables other than gadgets) in one hierarchy table! But I can't see how I can get my EF POCO classes to 'bottom-out' at Gadgets, yet still have Gadgets use the base Entity Id property so they can be used in the generic repository. Can anyone help?-


You do not have to map Entity class. Introducing DbSet<Entity> will map Entity class. If you are going to sore different types of Gadgets in a single table, then map the Gadget and other sub classes.

The properties declared in Entity` class will be used by EF to map the sub classes.

0

精彩评论

暂无评论...
验证码 换一张
取 消