1

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.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670

2 Answers2

1

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.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Would it it instead be possible to try something like: `public virtual int SourceID { get; set; }` and then just cast it to either a BuzzItem or Merchant object using RTTI? If so, do you have any tips on how I could implement it as such? – Justin Holdsclaw Jun 17 '11 at 05:33
1

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

Community
  • 1
  • 1
Damir Sudarevic
  • 21,891
  • 3
  • 47
  • 71
  • +1 because this is technically the solution I was looking for. But just as in the other question you linked to, an Entity superclass would server no purpose other than having an EntityID variable with no common properties, which as they pointed out isn't a good design. However, I'm not one to hold back legitimate solutions based solely upon strict design principles, so I might go with this route. Still hoping there is a more elegant approach out there, though. – Justin Holdsclaw Jun 17 '11 at 12:49