1

我正在尝试使用继承在 EF6 中实现模型

我有以下课程:
基本
评论
页面:基本
博客帖子:基本

Page 和 BlogPost 都以相同的方式使用评论。所以我将 Base 定义为

public class Base
{
    public int ID { get; set; }
    // ...
    public ICollection<Comment> Comments { get; set; }
}

并且评论类定义如下:

public class Comment
{
    public int ID { get; set; }
    public int RelatedItemID { get; set; } // points to Base::ID
    public string Text { get; set; }
}

假设我想将数据库设置为“每种类型的表”,因此 Page 和 BlogPost 都有单独的表,每个表都具有自动增量 int PK。

现在 EF 知道 Comment.RelatedItemID 指向哪个表了吗?即页面或博客帖子

无需求助于“每个层次结构的表”来实现这一点的最佳方法是什么?

4

1 回答 1

2

我想将数据库设置为“每种类型的表”,因此 Page 和 BlogPost 都有单独的表,每个表都具有自动增量 int PK

这是一个问题。
描述看起来像 TPC,但由于您想为每个后代使用自动增量主键,它不适合 TPC,因为最终您将在一个实体集中获得重复的主键。显然,它也不是TPT,因为 TPT 假设存在一个具有自动增量 ID 的“基”表,而“派生”表具有非自动增量主键,同时也是外键“基础”表。

在我看来,逻辑上这些实体是不相关的。我的意思是,在任何情况下,您都不会想要使用单个查询来查询页面和博客文章。因此,最好避免在 EF 模型中继承。

我建议您以这种方式重新设计模型:

// "abstract" tells EF, that this type doesn't require mapping
public abstract class CommentBase
{
    public int ID { get; set; }
    public int RelatedItemID { get; set; }
    public string Text { get; set; }
}

public class PageComment: CommentBase {}
public class BlogPostComment :  CommentBase {}

public abstract Base<TComment>
    where TComment : Comment
{
    public int ID { get; set; }
    // ...
    public ICollection<TComment> Comments { get; set; }
}

public class Page : Base<PageComment> { /* other page properties */ }
public class BlogPost : Base<BlogPostComment> { /* other blog post properties */ }

代码中仍然存在继承,但EF模型中会有两个不同的实体集。OTOH,您将获得两个带有评论的单独表格 - 一个用于页面,一个用于博客文章。

于 2015-08-12T08:58:46.583 回答