Click here to Skip to main content
13,506,716 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


4 bookmarked
Posted 7 Jan 2013

How to do a polymorphic association like Rails using Entity Framework

, 7 Jan 2013
Rate this:
Please Sign up or sign in to vote.
How to do a polymorphic association like Rails using Entity Framework


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 };
Quest quest = new Quest();
quest.Tags = new List<Tag> { ... lots of tags };
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. 


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


About the Author

fernando albernaz
Architect BNP Paribas
Brazil Brazil
No Biography provided

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180417.1 | Last Updated 7 Jan 2013
Article Copyright 2013 by fernando albernaz
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid