简体   繁体   中英

EF Core, how to map two entities on different properties

I am struggling to set up a relationship between two entity types which can be linked on multiple One-To-Many or Many-To-Many relationships, depending on the property considered.

On the following example, a student can be on multiple soccer teams and on different positions for example. Let's forget that a student can be only once in every soccer team, this is dealt from the application side.

I know that Many-To-Many relationships are not natively supported by EF-Core and that I shoud create intermediate tables with composite keys StudentSoccerTeam , but should I create one per property (Trainer, GoalKeeper, Strikers, Defenders)? Is there anything simpler which would accomodate both?

Thanks for your help,

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class SoccerTeam
{
    public int Id { get; set; }
    public string AwesomeName { get; set; }
    public Student Trainer { get; set; }
    public Student GoalKeeper { get; set; }
    public ICollection<Student> Strikers { get; set; }
    public ICollection<Student> Defenders { get; set; }

}

public class SoccerApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public SoccerApplicationDbContext(DbContextOptions options) : base(options)
    {
    }


    public DbSet<Student> Students { get; set; }
    public DbSet<Student> SoccerTeam { get; set; }

}

You have to add two tables:

For positions:

public class Positions
{ 
[Key]
public int Id {get; set;}
public string Name {get; set;}

}

and to keep many-to-many relationships ( with 3 foreign keys):

public class StudentSoccerTeam
{ 
[Key]
public int Id {get;set;}
public int TeamId {get; set;}
public int StudentId {get; set;}
public int PositionId {get; set;}
}

and remove these from SoccerTeam, you don't need them ( for example a team trainer will a Student wit Trainer position in StudentSoccerTeam table):

public Student Trainer { get; set; }
    public Student GoalKeeper { get; set; }
    public ICollection<Student> Strikers { get; set; }
    public ICollection<Student> Defenders { get; set; }
```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM