EF Core 将查询重写为升级后可翻译的形式

Tre*_*ild 5 linq entity-framework .net-6.0

在我们升级之前,这个查询运行良好:

var appUsers = await _masterDbContext
                      .Users
                      .Include(x => x.UserCustomers)
                      .AsNoTracking()
                      .Select(AppUserDto.Projection)
                      .Where(user => !user.IsDeleted && user.UserCustomers.Any(x => x.CustomerId == tenant.Id && x.UserId == user.Id))
                      .DistinctBy(x => x.Id)
                      .ToDataSourceResultAsync(request.GridOptions, cancellationToken: cancellationToken);
Run Code Online (Sandbox Code Playgroud)

我们现在收到错误:

Either rewrite the query in a form that can be translated, 
or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 
'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. 
Run Code Online (Sandbox Code Playgroud)

看来 DistinctBy 是罪魁祸首,但我对 LINQ 相当陌生,我不知道如何重写它以使其正常工作。

Moh*_*oho 4

更改DistinctByDistinct()并将其和谓词移至 之前Select。我还AsNoTracking()向上移动了:

var appUsers = await _masterDbContext
    .Users
    .AsNoTracking()
    .Include(x => x.UserCustomers)
    .Where(user => 
        !user.IsDeleted 
        && user.UserCustomers
            .Any( x => x.CustomerId == tenant.Id ) )
    .Distinct()
    .Select(AppUserDto.Projection)
    .ToDataSourceResultAsync(request.GridOptions, cancellationToken: cancellationToken);
Run Code Online (Sandbox Code Playgroud)