Entity Framework 1-To- * and 1-to-1

(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(); // Error here } 

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?

+6
source share
1 answer

The problem you are facing is that you are creating two relationships between two identical tables, and EF cannot tell which relationship the BlogEntity navigation property is BlogEntity . Using a quick api, you can directly say this, data annotations are not needed then.

 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); 
+2
source

Source: https://habr.com/ru/post/988152/


All Articles