添加類,如下所示:
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);
UPDATE:
看起來你其實想要這個:
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; }
}
您需要自己設置交接表(StaffSchedules),並從Staff和Schedules運行與該表的1:M關係。您可以在上下文文件中使用流利API配置映射。 – RizJa