包含附加字段的多对多,实体框架

时间:2016-11-30 20:09:12

标签: c# database entity-framework

我如何使用添加字段映射自定义多对多关系?在这种情况下,DateTime在Schedule中。

现在问题是它创建了一个名为StaffSchedules的新表

public class Schedule
{
    public int Id { get; set; }
    public DateTime DateTime { get; set; }

    public List<Staff> Staff { get; set; }
    public int StaffId { get; set; }

    public Patient Patient { get; set; }
    public int PatientId { get; set; }
}

public class Staff
{
    public int Id { get; set; }
    public string FirstName { get; set; }

    public List<Schedule> Schedules { get; set; }
}

...

public DbSet<Schedule> Schedules { get; set; }
public DbSet<Staff> Staff { get; set; }

期望的结果: enter image description here

1 个答案:

答案 0 :(得分:2)

像这样添加一个类:

public class StaffSchedule
{
    public int StaffId { get; set; }
    public int ScheduleId { get; set; }
    public virtual Staff Staff { get; set; }
    public virtual Schedule Schedule { get; set; }

    public DateTime Date { get; set; }
}

修改您的员工和日程安排课程:

public class Schedule
{
    public int Id { get; set; }
    //Other Fields
    public ICollection<StaffSchedule> StaffSchedules { get; set; }
}

public class Staff
{
    public int Id { get; set; }
    //Other Fields
    public ICollection<StaffSchedule> StaffSchedules { get; set; }
}

最后,在您的上下文文件(OnModelCreating方法)中:

modelBuilder.Entity<Staff>().HasKey(x => x.Id);
modelBuilder.Entity<Schedule>().HasKey(x => x.Id);

modelBuilder.Entity<StaffSchedule>().HasKey(x =>
    new
    {
        x.StaffId,
        x.ScheduleId
    });

modelBuilder.Entity<StaffSchedule>()
    .HasRequired(x => x.Staff)
    .WithMany(x => x.StaffSchedules)
    .HasForeignKey(x => x.StaffId);

modelBuilder.Entity<StaffSchedule>()
    .HasRequired(x => x.Schedule)
    .WithMany(x => x.StaffSchedules)
    .HasForeignKey(x => x.ScheduleId);

<强>更新

看起来你真的想要这个:

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

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

public class Schedule
{
    public int Id { get; set; }
    public DateTime Date { get; set; }

    public int PatientId { get; set; }
    public int StaffId { get; set; }

    [ForeignKey("PatientId")]
    public virtual Patient Patient { get; set; }
    [ForeignKey("StaffId")]
    public virtual Staff Staff { get; set; }
}