使用 EF Core 5 和 ASP.NET Core 3.1,我試圖根據其孫子集合的條件來獲取過濾集合。我有以下物體:
public class Organisation
{
public int Id { get; set; }
public int? OrganisationId { get; set; }
public IEnumerable<Customer> Customers { get; set; }
}
public partial class Customer
{
[Key]
public uint Id { get; set; }
public int? EmployerId { get; set; }
public int? OrganisationId { get; set; }
public List<TimecardProperties> TimecardsProperties { get; set; }
}
public partial class TimecardProperties
{
[Key]
public int Id { get; set; }
public int? EmployerId { get; set; }
public int? Week { get; set; }
public short? Year { get; set; }
}
目標是讓所有組織至少擁有一個客戶并且該客戶至少有 1 個時間卡屬性位于week=34和中year=2021。
到目前為止,我已經嘗試了以下方法:
////necessary join to get Organisations for user id
IQueryable<Organisation> ouQuery = (from cou in _dbContext.Organisations
join uou in _dbContext.table2 on cou.OrganisationId equals uou.OrganisationId
where uou.UsersId == int.Parse(userId)
select cou)
.Where(cou => cou.Customers.Where(c => c.TimecardsProperties.Count > 0).Any())
.Include(cou => cou.Customers.Where(c => c.TimecardsProperties.Count > 0))
.ThenInclude(c => c.TimecardsProperties.Where(tc => tc.tWeek == 34 && tc.Year > 2020))
;
這將回傳一個organisation串列,每個串列都有一個customers串列,但一些客戶的計數為timecards0。我不希望organisation在回傳的串列中沒有timecards集合中的至少一個專案。
此外,它太慢了,如果我嘗試過濾生成的串列,它會更慢(超過 15 秒)
我也嘗試了一個原始的 sql 查詢,organisation db context但它又很慢:
select distinct count(id) from organisation a where organisation_id in (
select organisation_id from customers where employer_id in (select distinct employer_id from timecards a
inner join timecard_components b on a.id=b.timecards_id
where week IN(
34) and year in (2021,2021) and invoice !=0 and type = 'time'
group by employer_id, week)
);
一般來說,我想知道回傳的分頁集合的總數organisation(所以我不需要包括每個物體的所有屬性)以及只回傳滿足條件的正確結果的一部分,一個通過最后執行查詢,organisation串列中至少有 1 個timecards,如下所示:customers
ouQuery.Skip((page - 1) * pageSize).Take(pageSize).ToListAsync();
我也嘗試了 EntityFramework.Plus 和沒有結果的投影。我怎么能寫這個來獲得organisation串列的總數和這些結果的一部分(前 10 個)以顯示給用戶?
uj5u.com熱心網友回復:
使用導航屬性。這是您想要的查詢:
var orgsQuery = dbContext.Organizations
.Where( o => o.Customers.Any( c =>
c.TimecardProperties.Any( tp =>
tp.Year = 2021
&& tp.Week = 34 ) ) );
根據需要添加包含和其他謂詞
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/414078.html
標籤:
上一篇:HttpContext不包含GetOpenIddictServerRequest的定義
下一篇:.NETCore后備日志記錄
