EF Code First, how can I achieve two foreign keys from one table to other table?

好久不见. 提交于 2019-12-12 09:43:21

问题


I've recently downloaded Entity Framework Code First CTP5, and have a trouble with this scenario. I have two tables as follows:

Members table :
  ID  
  Name

Comments table :  
  ID  
  Comment  
  CommentedMemberID  
  CommentMemberID  

And, the data should be like the following:

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 coded 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 "Cannot create CommentMember instance" or something like that (Sorry, I already changed my models to proceed the EF Code First evaluation, so can't reproduce the same error).

I've also tried to use OnModelCreating on the TestContext, but can't find any good instructions and don't know what to do. I saw a blog post of the EF Code First CTP3, and it seems there was a RelatedTo attribute in that version, but now it has gone.

Could anyone know how to get it work properly? Or is this a totally wrong way to go with this scenario?

Thanks,
Yoo


回答1:


This is a special case and you need to use fluent API to configure 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);
}


来源:https://stackoverflow.com/questions/4698233/ef-code-first-how-can-i-achieve-two-foreign-keys-from-one-table-to-other-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!