EF Code First 中的 ICommentable 接口 - 最佳实践

ICommentable interface in EF Code First - best practise

假设我有多个不相关的对象 (classes),我无法获得通用摘要 class(因此无法获得所有此类 classes 的唯一主键)。我还想将常见对象列表应用于所有此类 classes(例如评论列表)。我的第一种方法是这样的:

public class Comment
{
    public int Id { get; set; }
    public string CommentContent { get; set; }

    public virtual ICommentable CommentableObject { get; set; }
}

public interface ICommentable
{
    ICollection<Comment> Comments { get; set; }
}

public class Page : ICommentable
{
    public int Id { get; set; }
    public string PageContent { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
}

public class Post : ICommentable
{
    public int Id { get; set; }
    public string PostContent { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
}

EF code-first 所做的是创建单个 Comments table,具有多个可为空的外键(每个相关的 class 一个):Page_IdPost_Id.

备选方案之一是为每个 class 设置单独的评论 table:PageCommentsPostComments

对于这种常见情况,还有其他更优雅的解决方案吗?以上两种选择,哪一种更好?

我们在这里讨论的是 IsA (Is-A, Is A) 关系。您的选择在这里:http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph

它们本质上是将 is-a inheritance/implementation 映射到 is-a 数据库关系的方法。第二个选项(Table 每个类型)似乎以一种标准化的方式做到这一点,第三个选项我不熟悉。

在您的情况下,如果您确定只有 2 个 ICommentable 类,您可能希望坚持使用现有的。如果您改变了对它们都实现相同接口的想法,这也将使您更加灵活。规范化直到它受到伤害,非规范化直到它起作用。