0

我有两个表,Participant并且Meeting在 ASP.NET Core 6 最小 API 项目中设置如下:

record Participant(int id)
{
    public string name { get; set; } = default!;
    public string title { get; set; } = default!;
}

record Meeting(int id)
{
    public string subject { get; set; } = default!;
    public string organizer { get; set; } = default!;
    public DateTime starttime { get; set; } = default!;
    public DateTime endtime { get; set; } = default!;
}

class MyDb: DbContext 
{
    public MyDb(DbContextOptions<MyDb> options): base(options) 
    {
    }

    public DbSet<Participant> Participants => Set<Participant>();

    public DbSet<Meeting> Meetings => Set<Meeting>();
}

现在我需要创建一个连接这两个表/记录的组合表/记录

在 SQL 中,这将是这张表

CREATE TABLE meetings_participants
(
    meeting_id int NOT NULL,
    participant_id int NOT NULL,
    PRIMARY KEY (meeting_id, participant_id),
    CONSTRAINT fk_meeting_id 
        FOREIGN KEY (meeting_id) REFERENCES meetings(id),
    CONSTRAINT fk_participant_id 
        FOREIGN KEY (participant_id) REFERENCES participants(id)
);

但是我如何将它作为带有外键的记录写在 EF 中?

4

1 回答 1

1

您可以创建一个 MeetingParticipant 类,如下所示:

public class MeetingParticipant
{
    public int  ParticipantID { get; set; }
    [ForeignKey("ParticipantID")]
    public virtual Participant Participant { get; set; }
    public int MeetingID { get; set; }
    [ForeignKey("MeetingID")]
    public virtual Meeting Meeting { get; set; }
}

并更新 Participant 和 Meeting 类如下:

public record Participant(int id)
{
    public string name { get; set; } = default!;
    public string title { get; set; } = default!;

    public List<MeetingParticipant> MeetingParticipant { get; set; }
}

public record Meeting(int id)
{
    public string subject { get; set; } = default!;
    public string organizer { get; set; } = default!;
    public DateTime starttime { get; set; } = default!;
    public DateTime endtime { get; set; } = default!;
    public List<MeetingParticipant> MeetingParticipant { get; set; }
}

然后,更新 ApplicationDbContext (您可以将其更改为您的),如下所示:

public class ApplicationDbContext : IdentityDbContext
{ 
    public DbSet<Participant> Participants => Set<Participant>();

    public DbSet<Meeting> Meetings => Set<Meeting>();

    public DbSet<MeetingParticipant> MeetingParticipant { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    { 
        base.OnModelCreating(modelBuilder);
        //set the primary key
        modelBuilder.Entity<MeetingParticipant> ().HasKey(mp=> new { mp.MeetingID, mp.ParticipantID}); 
    }

然后,使用 EF 迁移命令启用迁移,如下所示(如果使用 Visual Studio):

Add-Migration AddMeetingParticipant
Update-Database

然后,它会在 Participant 和 Meeting 表之间配置多对多,MeetingParticipant 表用于存储关系。

有关 EF 核心关系的更多详细信息,请参阅以下文章:

多对多关系

在 Entity Framework Core 中配置多对多关系

于 2022-02-03T09:01:52.543 回答