Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core One to Many

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?

like image 683
tscrip Avatar asked Mar 20 '26 02:03

tscrip


1 Answers

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");
}
like image 199
Gert Arnold Avatar answered Mar 22 '26 15:03

Gert Arnold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!