实体框架4.1 - 将实体分成多个表(代码优先)

时间:2012-02-12 12:52:21

标签: asp.net-mvc-3 ef-code-first

我正在尝试找出如何在我的应用程序中“可评论”的多个场景中重复使用简单的“注释”实体类型。

目前,我有几个用户可以发表评论的实体。示例包括博客,个人资料和照片 - 这些都可以“评论”。

我希望能够为每个场景使用相同的“评论”类,但我不想最终得到一个充满了对所有内容的评论的巨大表。我认为至少存储一个BlogComments,PhotoComments和ProfileComments表会更有效率。目前,我的评论类看起来像这样:

public class Comment
{
   [Key]
   public int Id { get; set; }

   public int ContextId { get; set; }

   [StringLength(256)]
   public string Content { get; set; }

   public DateTime DatePosted { get; set; }

   public virtual Member Author { get; set; }
}

据推测,我需要'ContextId'字段来引用被评论的特定内容。此ID可能是博客,个人资料或照片的ID。我希望能够像这些类中的普通ICollection一样引用注释,并且我有一些像这样的代码作为示例:

public class Photo
{
    [Key]
    public int Id { get; set; }

    [StringLength(48)]
    public string FileName { get; set; }

    public virtual Member Owner { get; set; }

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

在我的搜索过程中,我一直被指向各种文章,但似乎没有一个与我的特定情况相关。如何将这些注释集合映射到不同的表,并避免使用注释“超级表”?

非常感谢任何帮助,指示或建议:)

1 个答案:

答案 0 :(得分:1)

您可以创建一个抽象的Comment类,并从中继承特定的注释,例如PhotoCommentProfileComment。您可以将注释映射到不同的表。

public abstract class Comment
{
   [Key]
   public int Id { get; set; }

   [StringLength(256)]
   public string Content { get; set; }

   public DateTime DatePosted { get; set; }

   public virtual Member Author { get; set; }
}


public class PhotoComment : Comment
{
   public int PhotoId { get; set; }

   public virtual Photo Photo { get; set; }
}


public class Photo
{
    [Key]
    public int Id { get; set; }

    [StringLength(48)]
    public string FileName { get; set; }

    public virtual Member Owner { get; set; }

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