簡體   English   中英

可以將Entity Framework配置為在沒有數據庫關系的情況下加載集合屬性嗎?

[英]Can Entity Framework be configured to load a collection property where there is no database relationship?

如果我在EF6實體類上設置了一個收集屬性,該屬性希望包含數據庫中的一組參考數據,那么由於兩個數據庫表之間沒有關系,是否可以將EF配置為自動加載該屬性? 我將以醫生的約會系統為例進行說明:

[Table]
public class Doctor 
{
    public Collection<Slot> AppointmentTimes { get; set; }
}

[Table]
public class Slot
{
    [Column]
    public DateTime StartTime { get; set; }

    [Column]
    public DateTime EndTime { get; set; }
}

每個醫生的約會時間都相同。 我認為當前的解決方案是DbContext中的一種hacky方法:

public Doctor FindDoctor(int id)
{
     var doctor = this.Doctors.Find(id);

     // I would rather have EF do this for me in the above Find() call
     if (doctor != null)
     {                
         foreach (var slot in this.Slots.ToList())
         {
            doctor.AppointmentTimes.Add(slot);
         }
     }

    return doctor;
}

當然可以。 打開您的EDMX,創建一個新的關系(edmx映射關系而不是數據庫關系)並保存。

我在說數據庫優先方法

您在這里描述的是一個獨立的關聯,即實體框架https://msdn.microsoft.com/en-gb/data/jj713564.aspx

var doctor = context.Doctors.First(c=>c.Id == id); 
context.Entry(doctor ).Reference(c => c.AppointmentTimes ).Load();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM