views:

102

answers:

3

Hey guys,

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.

A: 

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.

dario
+1  A: 

This does not call for polymorphism (inheritance).

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

Henk Holterman
A: 

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.

Hightechrider