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

Posted by Yoo Matsuo on Stack Overflow See other posts from Stack Overflow or by Yoo Matsuo
Published on 2011-01-15T05:44:05Z Indexed on 2011/01/15 5:53 UTC
Read the original article Hit count: 136

Filed under:

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 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 Members { get; set; }
 public DbSet 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

© Stack Overflow or respective owner

Related posts about entity-framework