renakre
renakre

Reputation: 8291

dilemma on the use of inheritance in EF code-first

I am trying to implement Like functionality (similar to Facebook) in my application. I will have three types of Likes: likes for posts, likes for comments (to the posts), and likes for replies (to the comments). Later, based on the like activities I want to generate a dynamic notification list for the user.

For this task, I thought inheritance would work great, so I have the following classes (Like is the base class)

Like : LikeId, LikeDate, WhoLiked, WhoseLiked, IsNotificationRead

PostLike: PostId

CommentLike: CommentId

ReplyLike: ReplyId

I need to generate a notification list that looks like:

  1. User1 liked your post (PostId should be attached to this item)

  2. User2 liked your comment (CommentId should be attached to this) item)

  3. User3 liked your reply (ReplyId should be attached to this item)

However, I am having hard time to generate this output for the last 2 days. Finally, I concluded that I cannot use dbcontext.Likes within a single LINQ statement to have this output.

I am planning to generate the list separately for each inherited entity and merge all lists at the end:

  var postlikes = db.Like.OfType<PostLike>().Select(a => 
         new {Text = "User1 liked your post", ItemId=a.PostId, Type="Post"});

  var commentlikes = db.Like.OfType<CommentLike>().Select(a => 
         new {Text = "User1 liked your comment", ItemId=a.CommentId, Type="Comment"});

  var replylikes = db.Like.OfType<ReplyLike>().Select(a => 
         new {Text = "User1 liked your reply", ItemId=a.ReplyId, Type="Reply"});

Do you think the way I implemented Inheritance makes sense in this scenario? Do you recommend an another approach? Do you think I need inheritance here?

Thanks

Upvotes: 2

Views: 66

Answers (1)

Chris Curtis
Chris Curtis

Reputation: 1478

Unless you have additional members elided from your example, your approach seems overkill. Plus doing 3 queries just to get likes for a notification seems heavy.

A simple implementation would be to have a single Like class with TargetId and TargetType properties, then just adjust the text according the the value of TargetType. You wouldn't get navigation properties that way, but you might not need them.

If you wanted your inherited classes like your example, at least refactor so you hit the database only once:

var likes = db.Like.ToList();

var postLikes = likes.OfType<CommentLike>()...

Upvotes: 2

Related Questions