2016-11-30 56 views
0

如何映射自定義與添加字段的多對多關係?在這種情況下Schedule中的DateTime。多對多有多餘字段,實體框架

現在的問題是它創建了一個名爲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

+0

您需要自己設置交接表(StaffSchedules),並從Staff和Schedules運行與該表的1:M關係。您可以在上下文文件中使用流利API配置映射。 – RizJa

回答

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); 

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; } 
} 
+0

這會創建工作人員,工作人員計劃和時間表。我現在做錯了什麼? –

+0

發表了我的意思,不知道我是否現在想錯了,但 –

+0

更新了答案。希望有所幫助。 – RizJa