Using entity framework (with MVC, but I think that’s irrelevant), I’m trying to make an entity that’s…extensible.
I have a number of classes that users can label as favorites or bookmarks…there’s actually several different objects that utilize this functionality. The way I currently have this implemented in my model is like this (as an example):
public class Favorite
{
[key]
public int FavoriteId {get; set;}
public int? BikeId {get; set;}
public virtual Bike Bike {get;set;}
public int? HelmetId {get;set;}
public virtual Helmet Helmet {get;set;}
public int? ShoeId {get;set;}
public virtual Shoe Shoe{get;set;}
public int UserId {get;set;}
public virtual User User {get;set;}
}
and the bike, helmet, user, and shoe class all resemble this:
public class Bike
{
public int BikeId {get;set;}
...
public virtual list<Favorties> Favorites {get;set;}
}
So currently my table looks like this:
Favorites:
| Id | BikeId | HelmetId | ShoeId | UserId |
| 1 | 5 | | | snowburnt |
| 2 | 6 | | | jonh |
| 3 | | 2 | | snowburnt |
I would prefer a structure for the favorite object where there is a differentiator column that stores the name of the object being reference as part of a multiple column primary key so that the favorites table looks more like this (I know the user ID isn’t an int):
Favorites:
| ID | Differentiator | foreignKeyId | UserId |
| 1 | Bike | 5 | snowburnt |
| 2 | Bike | 6 | john |
| 3 | Helmet | 2 | snowburnt |
The primary reason for wanting to do this is so that if I have new objects that I want to integrate into favorites I won’t have to modify the structure of the favorites object.
The hierarchy should be something like:
Bike, helmet, etc have 0 to many favorites
Is this possible in asp.net entity framework? How can I do this? Any good references out there for getting deep into the entity framework?
One note: I’ve seen the posts here, http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx which would work great…If I had an inheritance situation here (most of the reason I can’t have an inheritance situation is that I have multiple classes or interfaces that require the same relationship: favorites, bookmarks, comments, reviews, etc). It’s very probably that I could/should use interfaces for the favorites (make bike, helmet Favoritables). I haven’t found any notes on how that would end up mapping in the SQL Schema (would there even be a favorites table then?)
If you want to have table with described structure you must use ADO.NET and SQL for that. EF cannot map it. EF is only able to map real relations (referential constraints). Your table has no real relations – it has just data with some special meaning for your application and EF currently doesn’t support data driven mapping except some very simple scenarios like mentioned table per hierarchy inheritance. If you want to use EF you must live with the table structure you have at the moment.