[英]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)?我知道 EF-Core 本身不支持多对多关系,并且我应该使用复合键StudentSoccerTeam创建中间表,但是我应该为每个属性(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):并保持多对多关系(使用 3 个外键):
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):并从 SoccerTeam 中删除这些,您不需要它们(例如,团队教练将在 StudentSoccerTeam 表中成为学生机智教练 position):
public Student Trainer { get; set; }
public Student GoalKeeper { get; set; }
public ICollection<Student> Strikers { get; set; }
public ICollection<Student> Defenders { get; set; }
```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.