【问题标题】:Entity Framework 4.1 - Segregating an entity into multiple tables (Code-First)Entity Framework 4.1 - 将一个实体分离到多个表中(代码优先)
【发布时间】:2012-02-12 12:52:21
【问题描述】:

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

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

我希望能够为这些场景中的每一个使用相同的“评论”类,但我不想最终得到一个巨大的桌子,里面装满了所有的 cmets。我认为至少存储一个包含 BlogComments、PhotoComments 和 ProfileComments 的表会更有效率。目前,我的 Comment 类如下所示:

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 一样引用 cmets,并且我有一些像照片这样的代码作为示例:

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; }
}

在我的搜索过程中,我被指出了各种文章,但似乎没有一篇与我的具体情况真正相关。如何将这些评论集合映射到不同的表,并避免出现评论“超级表”?

任何帮助、指点或建议将不胜感激:)

【问题讨论】:

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


    【解决方案1】:

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

    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; }
    }
    

    【讨论】:

    • 太棒了!这是一个非常好的、简单的解决方案。我把问题复杂化了——谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2014-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多