Click here to Skip to main content
15,890,043 members
Articles / Entity Framework / Entity Framework 5.0
Tip/Trick

How to do a polymorphic association like Rails using Entity Framework

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
7 Jan 2013CPOL1 min read 11.8K   207   4  
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:

 Image 1

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 

C#
Article article = new Article();
article.Tags = new List<Tag> { ... lots of tags };
dbContext.Articles.Add(article);
dbContext.SaveChanges();  
C#
Quest quest = new Quest();
quest.Tags = new List<Tag> { ... lots of tags };
dbContext.Articles.Add(quest);
dbContext.SaveChanges(); 
C#
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. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect BNP Paribas
Brazil Brazil
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --