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 { g开发者_JAVA百科et; 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.
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.
Use this pattern, which can be achieved by using table-per-type inheritance in EF.
精彩评论