如何在SQL中执行此EF Core嵌套日期比较查询

时间:2018-09-28 16:53:38

标签: c# sql-server linq asp.net-core entity-framework-core

使用.Net Core 2.1和EF Core 2.1.1和SQL Server

我正在尝试提取Organizations的列表及其Communications的列表
然后,我想将其限制为在过去6个月内没有任何Communications的人

这是我略过的ViewModel:

public class OrganizationViewModel
{
    public Guid Id { get; set; }
    public IEnumerable<CommunicationViewModel> CommunicationViewModels { get; set;
}

public class CommunicationViewModel
{
    public Guid Id { get; set; }
    public DateTime Date { get; set; }

    public Guid OrganizationViewModelId { get; set; }
    public OrganizationViewModel OrganizationViewModel { get; set; }
}

这是我的查询:

DateTime sixMonthsAgo = DateTime.Today.AddMonths(-6);
int pageIndex = 1; // Would be passed in
int pageSize = 3;

IQueryable<OrganizationViewModel> query = _context.Organizations
    .AsNoTracking()
    .Select(organization => new OrganizationViewModel
    {
        CommunicationViewModels = organization.Communications.Select(communication => new CommunicationViewModel
        {
            Date = communication.Date
        })              
        .OrderByDescending(communication => communication.Date)
        .Take(1)
        .ToList()
    })
    .Where(organization => 
        (!searchViewModel.LimitToLastSixMonths || 
            organization.CommunicationViewModels.Any(communication => communication.Date <= sixMonthsAgo)));

int totalAmount = await query.CountAsync();
List<OrganizationViewModel> items = await query
            .Skip((pageIndex - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

这为我带来了预期的结果,但是当我按下.CountAsync()和。Skip(..).Take(..)时,在日志中可以看到我对每条记录执行此查询:

SELECT CASE
    WHEN EXISTS (
        SELECT 1
        FROM (
            SELECT TOP(1) [comm].[Date]
            FROM [Communications] AS [comm]
            WHERE @_outer_Id = [comm].[OrganizationId]
            ORDER BY [comm].[Date] DESC
        ) AS [t]
        WHERE [t].[Date] <= @__sixMonthsAgo_0)
    THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
END

调用.CountAsync()(稍作编辑)时,我还会看到这些警告:

  

Microsoft.EntityFrameworkCore.Query:警告:LINQ表达式
  'where (False OrElse {from CommunicationViewModel cvm in {from Communication comm in value(..EntityQueryable'1[..Models.Communication]) orderby [comm].Date desc where ?= (Property([o], "Id") == Property([comm], "OrganizationId")) =? select new CommunicationViewModel() {Date = [comm].Date} => Take(1) => AsQueryable()} where ([cvm].Date <= __sixMonthsAgo_0) select [cvm] => Any()})'无法翻译,将在本地进行评估。
  Microsoft.EntityFrameworkCore.Query:警告:LINQ表达式'Count()'无法翻译,将在本地进行评估。

调用.Take(..).Skip(..)时出现类似错误:

  

Microsoft.EntityFrameworkCore.Query:警告:LINQ表达式
  same as above无法翻译,将在本地进行评估。   Microsoft.EntityFrameworkCore.Query:警告:LINQ表达式'Skip(__ p_1)'无法翻译,将在本地进行评估。
  Microsoft.EntityFrameworkCore.Query:警告:LINQ表达式“ Take(__ p_2)”无法翻译,将在本地进行评估。

如果searchViewModel.LimitToLastSixMonths为假,则不会发生

关于如何重写查询以不对每个记录在本地执行该查询的任何建议吗?

2 个答案:

答案 0 :(得分:0)

如果您尝试将导航属性包含在select中,该怎么办?

IQueryable<OrganizationViewModel> query = _context.Organizations
    .Include(o => o.CommunicationViewModels)
...

答案 1 :(得分:0)

我知道了!

这是我的新查询:

DateTime sixMonthsAgo = DateTime.Today.AddMonths(-6);
int pageIndex = 1; // Would be passed in
int pageSize = 3;

IQueryable<OrganizationViewModel> query = _context.Organizations
    .AsNoTracking()
    .Select(organization => new OrganizationViewModel
    {
        CommunicationViewModels = organization.Communications.Select(communication  => 
            new CommunicationViewModel
            {
                Id = communication.Id,
                Date = communication.Date
            })
            .OrderByDescending(communicationViewModel => communicationViewModel.Date)
            .Take(1)
            .Where(communicationViewModel => communicationViewModel.Date <= sixMonthsAgo)
            .AsQueryable()
    })
    .Where(organizationViewModel =>
        (!searchViewModel.LimitToLastSixMonths || organizationViewModel.CommunicationViewModels.Any()));

int totalAmount = await query.CountAsync();
List<OrganizationViewModel> items = await query
            .Skip((pageIndex - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

searchViewModel.LimitToLastSizeMonthstrue时,这将产生以下两个查询:

SELECT COUNT(*)
FROM [Organizations] AS [organization]
WHERE EXISTS (
    SELECT 1
    FROM (
        SELECT [t].[Id], [t].[Date]
        FROM (
            SELECT TOP(1) [communication].[Id], [communication].[Date]
            FROM [Communications] AS [communication]
            WHERE [organization].[Id] = [communication].[OrganizationId]
            ORDER BY [communication].[Date] DESC
        ) AS [t]
        WHERE [t].[Date] <= @__sixMonthsAgo_0
    ) AS [t0])


SELECT [organization].[Id]
FROM [Organizations] AS [organization]
WHERE EXISTS (
    SELECT 1
    FROM (
        SELECT [t].[Id], [t].[Date]
        FROM (
            SELECT TOP(1) [communication].[Id], [communication].[Date]
            FROM [Communications] AS [communication]
            WHERE [organization].[Id] = [communication].[OrganizationId]
            ORDER BY [communication].[Date] DESC
        ) AS [t]
        WHERE [t].[Date] <= @__sixMonthsAgo_0
    ) AS [t0])
ORDER BY (SELECT 1)
OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY

在没有.AsQueryable()的情况下,它返回到检查每条记录并在本地执行计数和滑行/滑行。