Francisco Noriega
Francisco Noriega

Reputation: 14574

Error when having 2 properties/relationships of same type with EF4 Code First

I have a class X that has a many to many relationship with Y. If I only have that property then EF will correctly produce the 3rd XY table. However if I want to have that many to many relationship to type X AND also have a 1 to many relationship to Y.

To illustrate say I have something like this:

class Location
{
  public ICollection<Person> Visitors {get;set;}
}

class Person
{
  public Location Home {get;set}
  public ICollection<Location> VisitedPlaces {get;set;}
}

When I have both references, EF stops genereting the 3rd table and only gives me a 1 to 1 relationship for each property!

Upvotes: 0

Views: 111

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

You must add this to your derived context:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Person>()
        .HasRequired(p => p.Home)
        .WithMany()
        .WillCascadeOnDelete(false);
}

The problem is that EF is not able to infer correctly the mapping because it doesn't know if Visitors collection in Location class is part of declared many-to-many relation or one-to-many relation (it can't be part of both). My example defines that one-to-many relation doesn't have navigation property on Location so EF now knows that it is part of many-to-many relation.

Upvotes: 1

Related Questions