实体框架4.1代码优先 - 具有多种关系的外键?

时间:2011-06-17 02:03:17

标签: database-design entity-framework-4.1 ef-code-first

使用Entity中的代码优先方法,是否可以建立与单个外键绑定的多个关系?

例如,假设我有以下课程:

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; }
}

是否可以用一个可以建立双重关系的变量替换两个外键变量,并接受关系的BuzzItem或Merchant对象?

为了简洁起见,我从废料中提取了这个例子,所以如果我的代码中有任何拼写错误,我会道歉,但我希望清楚地了解我想要完成的事情。

2 个答案:

答案 0 :(得分:1)

不,不可能。 EF的行为与数据库完全相同 - FK与单一实体类型的单一关系紧密相关。顺便说一句。导航属性不是FK,FK隐藏在导航属性后面,但仍然如此 - 导航属性不能在多个关系之间共享。

答案 1 :(得分:1)

使用this pattern,可以使用 table-per-type inheritance in EF 来实现。

相关问题