Many to many Entity Framework code first

code-first ef-code-first entity-framework many-to-many

Question

I looked everywhere for a solution, but I couldn't...

First, I successfully constructed a many-to-many connection using code first. There is no limit to the number of clubs a person may belong to. TheClubPersons a new database table has been created.

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 must include the club's founder, who 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; }
}

Having done so, theClubPersons DB database has been removed and replaced with aClub_Id in thePeople desk andPerson_Id and Creator_Id in theClubs table.

As you can see, this won't function and when I attempt to add a person or club, I get the following error:

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

What is the right approach to define such a connection in code first, is my query. a lot to plenty to one

Thank you

1
10
4/5/2011 10:24:41 AM

Accepted Answer

Add the following technique 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 prevent EF from adopting a reciprocal arrangement with Club. the creator Person.Clubs

10
4/5/2011 4:19:48 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow