EF code First, how can I get two foreign keys from one table to another table?

I recently downloaded the Entity Framework Code First CTP5 and am having problems with this script. I have two tables:

  Members table:
   ID  
   Name

 Comments table:  
   ID  
   Comment  
   CommentedMemberID  
   CommentMemberID  

And the data should be such as:

  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  

Then I encoded as shown below:

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

But when I run these models on my cshtml , it gives me errors saying "Unable to instantiate CommentMember " or something like that (sorry, I already changed my models to continue evaluating EF Code First, so that doesn't reproduce same error).

I also tried using OnModelCreating on TestContext , but can't find any good instructions and don't know what to do. I saw the EF Code First CTP3 blog post, and it looks like there was a RelatedTo attribute in this version, but now it's gone.

Can anyone know how to make it work correctly? Or is this a completely wrong way to go with this scenario?

Thanks,
Yoo

+4
source share
1 answer

This is a special case and you need to use the free API to customize your associations. This will do the trick:

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

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


All Articles