Michael Willmott
Michael Willmott

Reputation: 529

Entity Framework Code First - Entity maps to one or the other

I have Entity1 and Entity2 for example:

public class Entity1
{
    public int Entity1ID { get; set; }
    public string Content { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

public class Entity2
{
    public int Entity2ID { get; set; }
    public string Content { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

I want to be able to add comments that are associated with each entity. This is easy enough if you were to have class Entity1_Comments and Entity2_Comments for example. Is there a way to store all the comments in one table though without confusion as to whether the record is mapping to an Entity1 record or Entity2 record?

You could for instance structure the comments table such that it has:

CommentID
Entity1_or_Entity2
ForeignKeyID
... 

as the table columns. Thereby checking which record type the comments is associated with using the column Entity1_or_Entity2 and then using the ForeignKeyID to find that record. I'm not sure how you might go about this using code-first though.

Thanks,

Michael

Upvotes: 2

Views: 188

Answers (2)

tdykstra
tdykstra

Reputation: 6060

One approach would be to set up TPH (table per hierarchy) inheritance on the Comment entity. That is, make a Comment base class, make Comment1 a derived class with FK to Entity1, and Comment2 a derived class with FK to entity 2. You end up with extra columns in your Comment table (two FKs instead of 1, plus a discriminator). See http://www.asp.net/entity-framework/tutorials/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application

Upvotes: 2

Diego Mijelshon
Diego Mijelshon

Reputation: 52745

Entity Framework does not support heterogeneous associations. Other frameworks handle this automatically (NHibernate, for example, provides the any mapping).

My solution is to mimic what NHibernate does, but manually.

There's a Comment entity with EntityType and EntityID fields, no foreign keys. A NoteService allows me to add/retrieve notes from any entity by storing/querying using those fields.

The only thing you will not have, of course, is direct navigation.

Upvotes: 1

Related Questions