Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework code first many to many

I've searched everyhwere but couldn't find an answer...

First, I have created a many to many relationship using code first which worked well. Each person can be in multiple clubs and each club can have multiple members. The ClubPersons table has been created in the DB.

public class Person
{
    public int PersonId { get; set; }
    public virtual ICollection<Club> Clubs { get; set; }
}

public class Club
{
    public int ClubId { get; set; }
    public virtual ICollection<Person> Members { get; set; }
}

Then I need to add the creator of the club which is also a person (one to many):

public class Club
{
    public int ClubId { get; set; }
    public virtual ICollection<Person> Members { get; set; }
    public virtual Person Creator { get; set; }
}

After doing this, the ClubPersons table in the DB has gone, replaced by a Club_Id in the People table and Person_Id and Creator_Id in the Clubs table.

As you can see, this won't work and it gives me the following error when I try to add person/club:

Multiplicity constraint violated. The role 'Person_Clubs_Source' of the relationship 'Test.Models.Person_Clubs' has multiplicity 1 or 0..1.

My question is what's the proper way to define such relationship in code first? Many to Many to One

Many thanks

like image 936
Leon Avatar asked Apr 05 '11 10:04

Leon


1 Answers

Add the following method to your context:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Club>().HasRequired(x => x.Creator) //or HasOptional
                               .WithMany() //Unidirectional
                               .Map(x => x.MapKey("Creator")) //FK column Name
                               .WillCascadeOnDelete(false);
}

That will keep EF from assuming a bidirectional relationship on Club.Creator <=> Person.Clubs

like image 134
Diego Mijelshon Avatar answered Oct 15 '22 00:10

Diego Mijelshon