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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?
1

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

1 Comment

+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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.