Justin Holdsclaw
Justin Holdsclaw

Reputation: 101

Entity Framework 4.1 Code First - Foreign Key with multiple relationships?

Using the code first method in Entity, is it possible to establish multiple relationships tied to a single foreign key?

For instance, say I have the following classes:

public class BuzzItem
{
    public int      BuzzItemID      { get; set; }
    public string   Title           { get; set; }
    public string   Description     { get; set; }

    // Collection of Comments posted about this BuzzItem (FOREIGN KEY)
    public virtual ICollection<Comment> Comments { get; set; }
}

public class Merchant
{
    public int      MerchantID      { get; set; }
    public string   Name            { get; set; }

    // Collection of Comments posted about this Merchant (FOREIGN KEY)
    public virtual ICollection<Comment> Comments { get; set; }
}

public class Comment
{
    public int      CommentID       { get; set; }
    public string   Comment         { get; set; }

    // These would both be a FOREIGN KEY to their respectivate tables
    public virtual BuzzItem BuzzItemID { get; set; }
    public virtual Merchant UserID { get; set; }
}

Is it possible to replace the two foreign key variables with a single variable that could establish a dual relationship and accept either a BuzzItem or a Merchant object for the relationship?

I drafted this example up from scrap for brevity sake, so I apologize if I have any typos in my code, but the general idea of what I'm trying to accomplish is hopefully clear.

Upvotes: 1

Views: 1322

Answers (2)

Damir Sudarevic
Damir Sudarevic

Reputation: 22187

Use this pattern, which can be achieved by using table-per-type inheritance in EF.

Upvotes: 1

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

No it is not possible. EF behaves exactly like database - FK is tight to single relationship with single entity type. Btw. navigation property is not FK, FK is hidden behind navigation property but the same is still true - navigation properties cannot be shared among multiple relations.

Upvotes: 1

Related Questions