Entity Framework Core One to Many
asp.net-core-1.0, asp.net-core-mvc, c#, entity-framework-core
Solution
There are several relationships between `Team` and `Member` and from `Member` to `Member`. If you only had this model ...
public class Member
{
public int Id { get; set; }
public string MemberName { get; set; }
public string MemberTitle { get; set; }
public Team MemberTeam { get; set; }
}
public class Team
{
public int Id { get; set; }
public string TeamName { get; set; }
public ICollection<Member> TeamMembers { get; set; }
}
... EF wouldn't need any help. It would understand that `Team.TeamMembers` and `Member.MemberTeam` are two ends of one association.
Now if you only add ...
public Member TeamSupervisor { get; set; }
... EF has to choose if this is the reverse end of a one-to-one association with `MemberTeam`, or a new association besides the one-to-many association. However, EF doesn't choose for you, you have to instruct it unambiguously, by mapping the associations explicitly. For example (in your `DbContext` subclass):
protected override void OnModelCreating(ModelBuilder mb)
{
mb.Entity<Team>().Property(a => a.Id).UseSqlServerIdentityColumn();
mb.Entity<Team>().HasMany(t => t.TeamMembers).WithOne(m => m.MemberTeam);
mb.Entity<Team>().HasOne(t => t.TeamSupervisor).WithMany()
.HasForeignKey("SupervisorId");
mb.Entity<Member>().Property(a => a.Id).UseSqlServerIdentityColumn();
mb.Entity<Member>().HasOne(m => m.MemberSupervisor).WithMany()
.HasForeignKey("SupervisorId");
}
Problem
I am trying to build a phone list with Entity Framework Core. Whenever I try to run the commend: `Add-Migration "Initial"` I get the following error: `Unable to determine the relationship represented by navigation property 'Member.MemberTeam' of type 'Team'. Either manually configure the relationship, or ignore this property from the model.` Here are my models: ``` public class Member { public int Id { get; set; } public string MemberName { get; set; } public string MemberTitle { get; set; } public Member MemberSupervisor { get; set; } public Team MemberTeam { get; set; } } public class Team { public int Id { get; set; } public string TeamName { get; set; } public Member TeamSupervisor { get; set; } public ICollection<Member> TeamMembers { get; set; } } ``` Any advice?