(实体框架6,.NET 4,VS 2010)
我创建了一个小型的Blog项目来说明问题。这是一个博客,有很多帖子,但只有一个帖子作为主要帖子。
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Post> PostEntities { get; set; }
public int? MainPostId { get; set; }
[ForeignKey("MainPostId")]
public virtual Post MainPostEntity { get; set; } // Problem here
}
public class Post
{
public int Id { get; set; }
public int BlogId { get; set; }
[ForeignKey("BlogId")]
public virtual Blog BlogEntity { get; set; }
public string Title { get; set; }
}
modelBuilder.Entity<Blog>()
.HasOptional(b => b.MainPostEntity)
.WithRequired(p => p.BlogEntity);
static void Main(string[] args)
{
Database.SetInitializer<EFTestContext>(null);
EFTestContext db = new EFTestContext();
Post[] posts = db.Posts.ToArray(); // Error here
}
如果删除导航属性public virtual Post MainPostEntity
,一切都按预期工作。但是,当我添加它时,我得到:
base {System.SystemException} = {"The ForeignKeyAttribute on property 'MainPostEntity' on type 'EFTest.Blog' is not valid. The foreign key name 'MainPostId' was not found on the dependent type 'EFTest.Post'. The Name value should be a comma separated list of foreign key property names."}
如果我删除了流畅的API调用,我会得到{"Invalid column name 'Blog_Id'."}
如果我将属性从[ForeignKey("MainPostId")]
更改为[ForeignKey("Id")]
,我会收到以下错误{"Invalid column name 'Blog_Id'."}
我做错了什么? 如何从Blog启用导航属性到主帖?
答案 0 :(得分:2)
您遇到的问题是您在同一两个表之间创建了两个关系,EF无法区分导航属性BlogEntity
所属的关系。使用流畅的api可以明确地告诉它,因此不需要数据注释。
modelBuilder.Entity<Blog>().HasMany(b => b.PostEntities).
WithRequired(p => p.BlogEntity).
HasForeignKey(p => p.BlogId).
WillCascadeOnDelete(true);
modelBuilder.Entity<Blog>().HasOptional(b => b.MainPostEntity).
WithMany().
HasForeignKey(b => b.MainPostId).
WillCascadeOnDelete(false);