簡體   English   中英

遷移一對多關系EF代碼優先

[英]migration one-to-many relationship EF code first aproach

我正在使用在LocalDb中使用EF 6.1.3的個人項目,首先使用了代碼,但在通過PM Console進行遷移時遇到了此錯誤:

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

我正在嘗試在帖子和評論類之間建立一對多關系。

這是郵政課:

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

我還有另外兩個一對多的關系,還有一對多的關系,但是好像它們在工作,所以我不知道問題出在哪里。

謝謝你的幫助。

這是您的問題:密鑰包含2個屬性

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

關系只有一個:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM