(Entity Framework 6, .NET 4, VS 2010)
I created a small blog project to illustrate the problem. This is a blog with many posts, but only one of the posts is the main post.
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();
If I remove the navigation property public virtual Post MainPostEntity , everything will work as expected. However, when I add it, I get:
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."}
If I remove the free API call, I get {"Invalid column name 'Blog_Id'."}
If I change the attribute from [ForeignKey("MainPostId")] to [ForeignKey("Id")] , I get the following error {"Invalid column name 'Blog_Id'."}
What am I doing wrong? How to enable the navigation property from the blog in the main post?
source share