Entity Framework Polymorphism

蓝咒 提交于 2019-12-23 03:19:11

问题


I wanted some help with trying to implement a simple polymorphic relationship using Entity Framework.

An example of a relationship I would like to implement:

Comment table

  • ItemType ('Video', 'User')
  • ItemID
  • Body

Video has many Comments

User has many Comments

No idea the best way to do this, I come from a Ruby on Rails way of thinking.


回答1:


This does not call for polymorphism (inheritance).

You state correctly: Video has Comments. Inheritance would require: Video is a Comment.




回答2:


Your basic choices are:-

1. Inheritance Model Videos and Users as sub-classes of Items either:-

1.1. Table-per-class inheritance (so one table for Video, one for Users)

1.2 Table-per-hierarchy inheritance (so one table that contains video and users together (some fields hidden for some types)

I suggest you look up table-per-class and table-per-hierarchy for Entity Framework.

2. Using generic interfaces (e.g. ICommentableObject<..>, ICommentableObjectContext<...>) This allows you to have separate Video, User, Comment tables and FKrelationships between then for VideoComment and UserComment (and more generally for any other tables you want to comment on).

This is do-able, but it's very complex. For example, I have an ITaggable implementation which can apply tags to any ObjectContext and any objects within it that support the given interface - but it wasn't easy.




回答3:


In my opinion you should model DB like this:

Tables:

Items (ItemID, ItemType, Body)

Users (UserID, ...)

Comments(CommentID, ItemID, UserID)

Then you shouln't have any problems to have relationships between your entities.



来源:https://stackoverflow.com/questions/2607414/entity-framework-polymorphism

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!