我最近下载了Entity Framework Code First CTP5
,但遇到了这种情况的问题。我有两张表如下:
Members table : ID Name Comments table : ID Comment CommentedMemberID CommentMemberID
并且,数据应如下所示:
Members ID Name 1 Mike 2 John 3 Tom Comments ID Comment CommentedMemberID CommentMemberID 1 Good 1 2 2 Good 1 3 3 Bad 2 1
然后,我编码如下:
public class Member
{
public int ID {get; set; }
public string Name { get; set;}
public virtual ICollection<Comment> Comments { get; set;}
}
public class Comment
{
public int ID { get; set; }
public string Comment { get; set; }
public int CommentedMemberID { get; set; }
public int CommentMemberID{ get; set; }
public virtual Member CommentedMember { get; set; }
public virtual Member CommentMember { get; set; }
}
public class TestContext : DbContext
{
public DbSet<Member> Members { get; set; }
public DbSet<Comment> Comments { get; set; }
}
但是当我在我的cshtml
上运行这些模型时,它会给我一些错误,说“无法创建CommentMember
实例”或类似内容(抱歉,我已经更改了模型以继续执行EF Code First评价,所以无法重现同样的错误)。
我还尝试在OnModelCreating
上使用TestContext
,但找不到任何好的说明,也不知道该怎么做。我看到了EF Code First CTP3的博客文章,看来该版本中有一个RelatedTo属性,但现在它已经消失了。
有谁知道如何让它正常工作?或者这是完全错误的方式吗?
谢谢,
柳
答案 0 :(得分:6)
这是一种特殊情况,您需要使用流畅的API来配置您的关联。这样就可以了:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Comment>().HasRequired(c => c.CommentedMember)
.WithMany(m => m.Comments)
.HasForeignKey(c => c.CommentedMemberID)
.WillCascadeOnDelete();
modelBuilder.Entity<Comment>().HasRequired(c => c.CommentMember)
.WithMany()
.HasForeignKey(c => c.CommentMemberID)
.WillCascadeOnDelete(false);
}