是否有任何優雅的方法可以對自己選擇的物件執行嵌套的 LINQ 選擇?換句話說,假設有三個資料庫表都具有一對多關系:Schedule,Day(一個計劃可能有很多天)和Activity(一天可能有很多活動。我想嘗試構建一個查詢它將資料選擇到相關的映射物件中,而無需創建額外的輔助物件。這是否可能?請參閱下面映射 DB 表的物件:
public Class Schedule{
public int ScheduleId { get; set; }
...
public byte[] RowVersion { get; set; }
[NotMapped]
public List<Day> days; //Supposed to store Day objects
}
public Class Day{
public int DayId { get; set; }
...
public byte[] RowVersion { get; set; }
[NotMapped]
public List<Activity> activities; //Supposed to store Activity objects
}
public Class Activity{
public int ActivityId { get; set; }
...
public byte[] RowVersion { get; set; }
}
此時,我使用其他類來獲取資料:SchedulePrim、DaysPrim 和 ActivitiesPrim。執行查詢后,我將 Prims 放入適當物件的 [NotMapped] 屬性中(見上文),然后擺脫 Prims。對我來說,這似乎使用了不必要的資源。查詢看起來有點像這樣:
from schedules in context.Schedules.Where(...)
select new SchedulePrim
{
Schedule = schedules
DaysPrim = from days in context.Days.Where(...)
select new DaysPrim
{
Day = days
ActivitiesPrim = from activities in context.Activities.Where(...)
select new DaysPrim
{
Activity = activities
}
}
}
這是將獲取的資料重新處理為適當物體的邏輯。有沒有更快的方法來做到這一點?讓動態選擇資料到 [NotMapped] 屬性的方式,而不需要引入額外的處理?
uj5u.com熱心網友回復:
只需消除 NotMapped 屬性和“附加類”,確保您有正確的外鍵,并使用 Include 加載資料。
db.Schedules.Include(s => s.Days).ThenInclude(d => d.Activities).Where(...)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494611.html
上一篇:EFCore將一個物件的一個??欄位映射到另一個物件的兩個不同欄位
下一篇:通過下拉串列過濾表的MVC顯示無
