【问题标题】:Entity Framework 4.1 Code First - Foreign Key with multiple relationships?Entity Framework 4.1 Code First - 具有多重关系的外键?
【发布时间】:2011-06-17 02:03:17
【问题描述】:

在Entity中使用code first方法,是否可以建立绑定到单个外键的多个关系?

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

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 对象作为关系的变量?

为了简洁起见,我从废品中起草了这个示例,因此如果我的代码中有任何拼写错误,我深表歉意,但希望我想要完成的总体思路很清楚。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 是否可以尝试类似:public virtual int SourceID { get; set; },然后使用 RTTI 将其转换为 BuzzItem 或 Merchant 对象?如果是这样,您对我如何实现它有什么建议吗?
    【解决方案2】:

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

    【讨论】:

    • +1 因为这在技术上是我正在寻找的解决方案。但就像您链接到的另一个问题一样,Entity 超类除了拥有一个没有公共属性的 EntityID 变量之外没有其他用途,正如他们指出的那样,这不是一个好的设计。但是,我不是一个仅仅基于严格的设计原则来阻止合法解决方案的人,所以我可能会选择这条路线。不过,仍然希望有一种更优雅的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2012-05-15
    • 1970-01-01
    • 2023-04-11
    • 2011-08-01
    相关资源
    最近更新 更多