迁移一对多关系EF代码首先是aproach

时间:2015-06-05 08:36:06

标签: c# ef-code-first entity-framework-6

我在LocalDb中使用EF 6.1.3开发个人项目,使用代码优先,但在使用PM控制台迁移时出现此错误:

Post_Comments_Source_Post_Comments_Target: : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical.

我正试图在Post和Comment Classes之间建立一对多的关系。

这里是Post Class:

    public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string ShortDescription { get; set; }
    public string Content { get; set; }
    public DateTime PostedOn { get; set; }
    public DateTime? Modified { get; set; }

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

}

}

评论类

  public class Comment
{
    public int CommentId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int PostId { get; set; }

    public virtual Post Post { get; set; }
}

帖子映射:

        public PostMap()
    {
        HasKey(t => t.PostId);

        Property(t => t.PostId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(t => t.Title).IsRequired();
        Property(t => t.ShortDescription);
        Property(t => t.Content).IsRequired();
        Property(t => t.PostedOn).IsRequired();
        Property(t => t.Modified);

        ToTable("Post");

    }

评论映射

 public class CommentMap : EntityTypeConfiguration<Comment>
{
    public CommentMap()
    {
        HasKey(t => new { t.CommentId, t.PostId });

        Property(t => t.CommentId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(t => t.Title).IsRequired();
        Property(t => t.Content).IsRequired();            

        ToTable("Comment");

        HasRequired(t => t.Post).WithMany(c => c.Comments).HasForeignKey(t => t.PostId).WillCascadeOnDelete(false);
    }
}

我有另外两个一对多的关系和一个多对多的关系,但似乎它们有效,所以我不知道问题出在哪里。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这是你的问题:密钥由2个属性组成

  

HasKey(t =&gt; new {t.CommentId,t.PostId});

只有一个关系:

  

HasRequired(t =&gt; t.Post).WithMany(c =&gt; c.Comments).HasForeignKey(t =&gt;   t.PostId).WillCascadeOnDelete(假);

请检查:http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx