首页 > 解决方案 > 使用代码优先的 Entiy 框架在模型类中建立关系

问题描述

我正在使用 asp.net mvc,对于数据部分,我使用的是代码优先方法,并且我有一个名为“Comment”的模型类。我想实现嵌套评论(我想要回复选项)。这是我的模型课:

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

    public int PostID { get; set; }

    //if it is null (or zero) , it is a father comment
    //if it is not null , it is a boy comment
    public int ParentID { get; set; }
    [Display(Name = "نام")]
    [Required(ErrorMessage = "لطفا نام خود را وارد کنید")]
    [DataType(DataType.Text)]
    [MaxLength(200)]

    public string CommentName { get; set; }
    [Display(Name = "ایمیل")]
    [Required(ErrorMessage = "لطفا ایمیل خود را وارد کنید")]
    [DataType(DataType.Text)]
    [MaxLength(200)]

    public string CommentEmail { get; set; }
    [Display(Name = "متن نظر")]
    [Required(ErrorMessage = "لطفا نظر خودرا بنویسید")]
    [DataType(DataType.MultilineText)]
    public string CommentText { get; set; }
    public DateTime CommentDate { get; set; }
    public bool IsCommentOk { get; set; }

    public virtual Post Post { get; set; }
    public virtual Comment Comment1 { get; set; }
    public virtual Lis<Comment> Comment2 { get; set; }
    public Comment()
    {

    }
}

我想在 'ParrentID' 和 'CommentID' 之间建立关系。如果 ParentID 为 0 ,则为普通评论,但如果它不为零,则表示回复评论,其值显示其父评论的 commentID。我使用以下代码实现了这个想法:

        public virtual Comment Comment1 { get; set; }
        public virtual List<Comment> Comment2 { get; set; }

但这不起作用。什么是问题,什么是解决方案?

标签: c#asp.netasp.net-mvcentity-framework-6

解决方案


尝试这个

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

    .....

    public int? ParentID { get; set; }
    
     public virtual Comment Parent { get; set; }

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

并将其添加到您的数据库上下文中

public class Context: DbContext 
{

    public DbSet<Comment> Comments { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       modelBuilder.Entity<Comment>()
            .HasOne(s => s.Parent)
            .WithMany(m => m.Children)
            .HasForeignKey(e => e.ParentID);
    }
}
  

推荐阅读