65.9K
CodeProject is changing. Read more.
Home

How to do a polymorphic association like Rails using Entity Framework

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jan 7, 2013

CPOL

1 min read

viewsIcon

12036

downloadIcon

208

How to do a polymorphic association like Rails using Entity Framework

Introduction

If you are trying to do something like polymorphic association just like ActiveRecord using Entity Framework for example act_as_taggable_on GEM.

This is how you can do using EF 5.0.

Using the code

We want to have a modeling like this:

 

And I don't care how the database will be, I just want EF do some magic and everything works fine.

So the Idea is that I have one or more classes that can be tagged and I have a class defining my tags, I want multiple entities to be related to multiple tags, something like this 

Article article = new Article();
article.Tags = new List<Tag> { ... lots of tags };
dbContext.Articles.Add(article);
dbContext.SaveChanges();  
Quest quest = new Quest();
quest.Tags = new List<Tag> { ... lots of tags };
dbContext.Articles.Add(quest);
dbContext.SaveChanges(); 
var article = dbContext.Articles.First();  
var quest = dbContext.Quests.First();   
 

Ok so Article has many Tags and Quest has many Tags I can save and select transparently  through EF.

But what is happening behind the scenes ?

Well, I have the following classes:

Tag, Article, Quest and a DbContext named dbContext the trick is my polymorphic class Taggable

Article and Quest inherit from Taggable and they don't have Id they inherit it by TPT.

So Taggable has a list of Tag which makes Article and Quest having it to, Tag has a list of Taggable which makes the EF create a intermediate transparent table between Tag and Taggable.

So that way you can have many classes having many Tags and any Tag having many Taggable.