简体   繁体   中英

Association inheritance with Entity Framework

Consider for instance my following database model.

  • UserTable(Id, Username)
  • TextContentTable(Id, Name, Description, CreatedByUserId, ModifiedByUserId, TextContent)
  • ImageContentTable(Id, Name, Description, CreatedByUserId, ModifiedByUserId, ImageContent)

I would like to create the following object model. But is it even possible? For instance:

  • BaseEntity(Id)
  • DescriptiveEntity(Name, Description) : BaseEntity
  • TrackedEntity( CreatedBy , ModifiedBy ) : DescriptiveEntity
  • User(Username) : BaseEntity
  • TextContent(Text) : TrackedEntity
  • ImageContent(Image) : TrackedEntity

I hope you understand my notation, but is it possible to map associations (marked in bold) to the individual tables TextContentTable & ImageContentTable?

Thanx in advance.

I'm not sure this approach is such a good idea with the current, shipping version of the Entity Framework. When a type, like TextContent inherits from a type like BaseEntity, it must have the same entity set as the base type. With the strategy outlined in the question, all entities in your application would have the same entity set. I'm not sure that's what you want.

However, you can get much the same effect via interfaces. For example, you could have an interface, IEntity which exposes an id property. Another interface, ITrackedEntity could expose CreatedBy and ModifiedBy. Etc.

This is not ideal, but it's more than good enough for us at present. We actually use codegen via T4 templates to implement these.

The next version of the Entity Framework may have features which make this inheritance pattern easier to implement without requiring a single entity 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