c# - 将多个外键映射到一个实体
问题描述
我正在设计包含两个实体的数据库。Match
和Team
。
public class Match
{
public int Id { get; set; }
public int TeamOneId { get; set; }
public int TeamTwoId { get; set; }
}
public class Team
{
public int Id { get; set; }
public List<Match> Matches { get; set; }
}
如您所见,Team
可以映射为TeamOne
或TeamTwo
。
我想同时映射Matches
到Team
依赖TeamOneId
和TeamTwoId
来自Match
实体。
我制作模型构建器:
public void Configure(EntityTypeBuilder<Team> builder)
{
builder.HasKey(x => x.Id);
builder
.HasMany(x => x.Matches)
.WithOne()
.HasForeignKey(x => x.TeamOneId)
.HasPrincipalKey(x => x.Id);
builder
.HasMany(x => x.Matches)
.WithOne()
.HasForeignKey(x => x.TeamTwoId)
.HasPrincipalKey(x => x.Id);
}
// matches
builder.ToTable("Matches");
builder.HasKey(x => x.Id);
builder.Property(x => x.TeamOneId).IsRequired();
builder.Property(x => x.TeamTwoId).IsRequired();
builder.Property(x => x.MatchDate).IsRequired();
但正如我所见,EF 无法正确映射它:
是否可以将两个 FK 从一个表映射到数据库中的另一个实体?
解决方案
I would take this approach, this of course is psudo code but this should help you get on your way.
builder.Entity<UserActivity>(x => x.HasKey(ua =>
new { ua.AppUserId, ua.ActivityId })); /// <-- this defines a concatenated key
builder.Entity<UserActivity>()
.HasOne(u => u.AppUser) /// <-- this says that the UserActivity has One AppUser
.WithMany(a => a.UserActivities) /// <-- to many User Activities
.HasForeignKey(u => u.AppUserId); /// <-- with this Foreign Key - App User Id
builder.Entity<UserActivity>()
.HasOne(a => a.Activity) /// <-- this says that the UserActivity has One AppUser
.WithMany(u => u.UserActivities) /// <-- to many User Activitiesthis Foreign Key
.HasForeignKey(a => a.ActivityId); /// <-- with this Foreign Key - Activity Id
推荐阅读
- javascript - 如何在javascript游戏中添加跳跃限制?
- sql - 在 SQL Server 中通过游标(获取表名)删除所有表
- python - 如何构建请求异常处理并检查 200 响应?
- database-design - DynamoDB:如何为带有标签(描述符)的项目设计模式?
- sql - 根据其他联接表列计算字段的总和
- r - 计算断开的子网数
- epub - 在 EPUB 文件中,什么会
意思是? - django - 前端代码直接访问http而不是https并导致混合内容错误
- python - 如何将列表变成contourf可以理解的2x2数组
- python - 在 C 中将浮点数转换为字符串,然后在 Python 中读取