开发者

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

开发者 https://www.devze.com 2023-02-04 03:38 出处:网络
I\'ve recently downloaded Entity Framework Code First CTP5, and have a trouble with this scenario. I have two tables as follows:

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


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

精彩评论

暂无评论...
验证码 换一张
取 消