首页 > 解决方案 > 将多个外键映射到一个实体

问题描述

我正在设计包含两个实体的数据库。MatchTeam

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可以映射为TeamOneTeamTwo

我想同时映射MatchesTeam依赖TeamOneIdTeamTwoId来自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 从一个表映射到数据库中的另一个实体?

标签: c#entity-framework-core

解决方案


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

推荐阅读