Click here to Skip to main content
Click here to Skip to main content

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

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. 

License

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

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 7 Jan 2013
Article Copyright 2013 by fernando albernaz
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid