在 EF Core 中,假設我的資料庫模型包含一個Patient具有相關集合的物體,如下所示:
public class Patient
{
// Patient properties
public int Id { get; set; }
public string Name { get; set; }
// Navigation properties
public List<Allergy> Allergies { get; set; }
public List<Medication> Medications { get; set; }
public List<Symptom> Symptoms { get; set; }
etc.
}
public class Allergy
{
public int Id { get; set; }
<more properties>
// Navigation properties
public int PatientId { get; set; } // FK to the related Patient
public Patient Patient { get; set; }
}
在我的實際代碼中,我有 8 種這樣的關系。如果我通過 LINQ 獲取 Patient 及其相關集合,EF 將創建一個具有 8 個連接的怪物查詢:
var qry = from patient in db.Patients
.Include(p => p.Allergies)
.Include(p => p.Medications)
.Include(p => p.Symptoms)
.Include(<etc.>)
where patient.Id = <desired Id>
select patient;
var Patient = await qry.FirstOrDefaultAsync();
我的另一個選擇是在不加載相關集合的情況下獲取 Patient,然后訪問資料庫 8 次以加載相關集合:
var qry = from patient in db.Patients
where patient.Id = <desired Id>
select patient;
var Patient = await qry.FirstOrDefaultAsync();
await db.Entry(Patient).Collection(p => p.Allergies).LoadAsync();
await db.Entry(Patient).Collection(p => p.Medications).LoadAsync();
await db.Entry(Patient).Collection(p => p.Symptoms).LoadAsync();
etc.
哪種策略更有效(執行速度更快)?是否有一個“快樂的中間地帶”,我用一個簡單的 SQL 查詢加載基本物體,然后只訪問資料庫一次以加載所有所需的相關集合?
(我找到了像這樣的 SO“答案” ,它依賴于當前的 EF 行為,例如“這有效,因為背景關系將檢測到您正在尋找的物體已經加載并已附加,因此不會創建一個新物體,而是更新舊的”。我對這些型別的解決方案的問題是,當 EF 實作細節發生變化時,它們可能會停止作業。)
uj5u.com熱心網友回復:
您可以像這樣在 EF Core中使用拆分查詢:
只需在鏈.AsSplitQuery()的末端呼叫即可。.Include()
EF 允許您指定應將給定的 LINQ 查詢拆分為多個 SQL 查詢。拆分查詢不是 JOIN,而是為每個包含的集合導航生成一個額外的 SQL 查詢。
var qry =
from patient in db.Patients
.Include(p => p.Allergies)
.Include(p => p.Medications)
.Include(p => p.Symptoms)
.Include(/* etc. */)
.AsSplitQuery() // <-- add this method call
where patient.Id = <desired Id>
select patient;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537632.html
標籤:C#实体框架实体框架核心
