计算其他 table 中未引用的记录(EF 和 LINQ 的一对多 table 问题)
Count records not referenced in other table (one-to-many table issue with EF & LINQ)
如何使用 计算 所有未开具发票(见下表)但应开具发票(可开票)的 TimeLog 记录,Entity Framework 和 Linq?
dbo.TimeLogs
[Table("TimeLogs")]
public class TimeLogEntity
{
int Id {get; set;}
int IsBillable {get; set;}
...
List<InvoiceEntity> Invoices {get; set;}
}
dbo.Invoices
[Table("Invoices")]
public class InvoiceEntity
{
int Id {get; set;}
int TimeLogId {get; set;}
bool IsActive {get; set;}
...
TimeLogEntity TimeLog {get; set;}
}
我试过了,但没有成功:
var numRows = await applicationDbContext.TimeLogs
.Include(t => t.Invoices.Where(i => i.IsActive == true))
.Where(t => t.IsBillable == true && t.IsActive == true && t.Invoices.Count == 0)
.CountAsync();
以上查询结果在此 SQL-查询(se below)中,它不检查发票记录是否有效。我不会计算 IsActive = false 的发票(它们被视为已删除)。
SELECT COUNT(*)
FROM [TimeLogs] AS [t]
WHERE (([t].[IsBillable] = CAST(1 AS bit)) AND ([t].[IsActive] = CAST(1 AS bit))) AND ((
SELECT COUNT(*)
FROM [Invoices] AS [i]
WHERE [t].[Id] = [i].[TimeLogId]) = 0)
我正在使用 Microsoft.AspNetCore.Identity.EntityFrameworkCore (6.0.1)
这个应该可以。请注意,引入Include
只是为了加载相关数据,而不是过滤主要记录。
var numRows = await applicationDbContext.TimeLogs
.Where(t => t.IsBillable == true && t.IsActive == true
&& !t.Invoices.Where(i => i.IsActive == true).Any())
.CountAsync();
如何使用 计算 所有未开具发票(见下表)但应开具发票(可开票)的 TimeLog 记录,Entity Framework 和 Linq?
dbo.TimeLogs
[Table("TimeLogs")]
public class TimeLogEntity
{
int Id {get; set;}
int IsBillable {get; set;}
...
List<InvoiceEntity> Invoices {get; set;}
}
dbo.Invoices
[Table("Invoices")]
public class InvoiceEntity
{
int Id {get; set;}
int TimeLogId {get; set;}
bool IsActive {get; set;}
...
TimeLogEntity TimeLog {get; set;}
}
我试过了,但没有成功:
var numRows = await applicationDbContext.TimeLogs
.Include(t => t.Invoices.Where(i => i.IsActive == true))
.Where(t => t.IsBillable == true && t.IsActive == true && t.Invoices.Count == 0)
.CountAsync();
以上查询结果在此 SQL-查询(se below)中,它不检查发票记录是否有效。我不会计算 IsActive = false 的发票(它们被视为已删除)。
SELECT COUNT(*)
FROM [TimeLogs] AS [t]
WHERE (([t].[IsBillable] = CAST(1 AS bit)) AND ([t].[IsActive] = CAST(1 AS bit))) AND ((
SELECT COUNT(*)
FROM [Invoices] AS [i]
WHERE [t].[Id] = [i].[TimeLogId]) = 0)
我正在使用 Microsoft.AspNetCore.Identity.EntityFrameworkCore (6.0.1)
这个应该可以。请注意,引入Include
只是为了加载相关数据,而不是过滤主要记录。
var numRows = await applicationDbContext.TimeLogs
.Where(t => t.IsBillable == true && t.IsActive == true
&& !t.Invoices.Where(i => i.IsActive == true).Any())
.CountAsync();