User4
User4

Reputation: 1350

Entity Framework 6.1.2 Many to Many

I am having trouble with entity framework 6.1.2. I'm sure this will have been covered before but I cant find it anywhere. On building the database entity framework wont create the relationships for the two list items I have because I have them declared as single entities above.

Is there any work around for this?

public class SomeClass
{
    public TeamMember LeadPartner { get; set; }
    public Team Team { get; set; }
    public List<TeamMember> OtherTeamMembers { get; set; }
    public List<Team> OtherTeams { get; set; }
}

Sorry if this has been asked before I really couldn't find anything on it.

Upvotes: 1

Views: 183

Answers (2)

kjbartel
kjbartel

Reputation: 10591

Add the mapping in your DbContext.OnModelCreating override similar to the following:

modelBuilder.Entity<SomeClass>()
            .HasMany<TeamMember>(sc => sc.OtherTeamMembers)
            .HasMany();
         // .HasMany(tm => tm.SomeClassNavigationPropertyList);

Upvotes: 1

ChrisV
ChrisV

Reputation: 1309

Most likely there is ambiguity in the other classes. For instance if you have a List<SomeClass> defined in Team, EF can't be sure whether this property is to partner with public Team Team (which would create a one-many relationship) or public List<Team> OtherTeams (creating a many-many relationship). Either is valid.

To resolve the ambiguity, add an [InverseProperty("OtherTeams")] annotation to the List<SomeClass> in the other classes.

Also, best practice is to expose the property as an ICollection<T> rather than a List<T>, creating a new List<T> or whatever in the constructor. This allows you to vary implementation later, for instance use a HashSet<T> instead.

Upvotes: 4

Related Questions