Home > front end >  Two one-to-one relationships in EF core
Two one-to-one relationships in EF core

Time:11-15

I'm trying to configure a one-two-one relationship twice for an entity with the following classes.

public class Team 
{
    ...
    public virtual TeamGraphic TeamLogo { get; set; }
    public virtual TeamGraphic TeamPlayer { get; set; }
}
public class TeamGraphic
{
    ...
    public virtual Team Team { get; set; }
}

TeamGraphics will be image data.

In the datacontext class

modelBuilder.Entity<Team>(t =>
{
    t.HasOne<TeamGraphic>(g => g.TeamLogo)
    .WithOne(t => t.Team);

    t.HasOne<TeamGraphic>(g => g.TeamPlayer)
    .WithOne(t => t.Team);
});

So to put it in words. A team can have one logo, and a team would have one player (image).

But when I try to do a migration, I get the error:

Cannot create a relationship between 'TeamGraphic.Team' and 'Team.TeamPlayer' because a 
relationship already exists between 'TeamGraphic.Team' and 'Team.TeamLogo'. Navigations can 
only participate in a single relationship. If you want to override an existing relationship 
call 'Ignore' on the navigation 'Team.TeamPlayer' first in 'OnModelCreating'.

Is this at all possible to do?

CodePudding user response:

Is full explained on error: "Navigations can only participate in a single relationship." That means you should to create a second Team on TeamGraphic

public class TeamGraphic
{
    ...
    public virtual Team TeamFromTeamLogo { get; set; }
    public virtual Team TeamFromTeamPlayer { get; set; }
}

modelBuilder.Entity<Team>(t =>
{
    t.HasOne<TeamGraphic>(g => g.TeamLogo)
    .WithOne(t => t.TeamFromTeamLogo);

    t.HasOne<TeamGraphic>(g => g.TeamPlayer)
    .WithOne(t => t.TeamFromTeamPlayer);
});

It has sense. If you only have one reverse navigation, TeamGraphic.Team, is ambiguous. "Which one"?

  • Related