实体框架代码优先 - 实体映射到一个或另一个

时间:2011-10-29 13:46:03

标签: entity-framework ef-code-first foreign-key-relationship

我有Entity1和Entity2,例如:

public class Entity1
{
    public int Entity1ID { get; set; }
    public string Content { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

public class Entity2
{
    public int Entity2ID { get; set; }
    public string Content { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

我希望能够添加与每个实体相关联的评论。如果您要使用class Entity1_CommentsEntity2_Comments,这很容易。有没有办法将所有注释存储在一个表中,但不会混淆记录是否映射到Entity1记录或Entity2记录?

例如,您可以构建注释表,使其具有:

CommentID
Entity1_or_Entity2
ForeignKeyID
... 

作为表格列。从而使用列Entity1_or_Entity2检查注释与哪个记录类型相关联,然后使用ForeignKeyID查找该记录。我不确定如何使用代码优先进行此操作。

谢谢,

迈克尔

2 个答案:

答案 0 :(得分:2)

一种方法是在Comment实体上设置TPH(每个层次结构的表)继承。也就是说,创建一个Comment基类,使Comment1成为带有FK到Entity1的派生类,而Comment2带有FK到实体2的派生类。最终在Comment表中有额外的列(两个FK而不是1,加上一个鉴别器) )。看到 http://www.asp.net/entity-framework/tutorials/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application

答案 1 :(得分:1)

实体框架不支持异构关联。其他框架自动处理这个问题(例如,NHibernate提供any映射)。

我的解决方案是模仿NHibernate的功能,但需要手动。

有一个Comment个实体,其EntityTypeEntityID字段,没有外键。 NoteService允许我通过使用这些字段存储/查询来添加/检索来自任何实体的注释。

当然,你唯一没有的就是直接导航。