4

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

RajeshKdev
  • 6,365
  • 6
  • 58
  • 80
Yoo Matsuo
  • 2,361
  • 2
  • 28
  • 41

1 Answers1

6

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);
}
Morteza Manavi
  • 33,026
  • 6
  • 100
  • 83
  • 1
    Thank you very much. That did the trick! I'll take a look at the fluent API since still don't get it how it works :) – Yoo Matsuo Jan 15 '11 at 14:14