【发布时间】:2020-01-07 17:57:40
【问题描述】:
//Model
public class Application
{
[Key]
public int ApplicationId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime ConfirmedDate { get; set; }
public DateTime IssuedDate { get; set; }
public int? AddedByUserId { get; set; }
public virtual User AddedByUser { get; set; }
public int? UpdatedByUserId { get; set; }
public virtual User UpdatedByuser { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string TRN { get; set; }
public string EmailAddress { get; set; }
public string Address { get; set; }
public int ParishId { get; set; }
public Parish Parish { get; set; }
public int? BranchIssuedId { get; set; }
public BranchLocation BranchIssued { get; set; }
public int? BranchReceivedId { get; set; }
public BranchLocation BranchReceived {get; set; }
}
public async Task<List<Application>> GetApplicationsByNameAsync(string name)
{
if (string.IsNullOrEmpty(name))
return null;
return await _context.Application
.AsNoTracking()
.Include(app => app.BranchIssued)
.Include(app => app.BranchReceived)
.Include(app => app.Parish)
.Where(app => app.LastName.ToLower().Contains(name.ToLower()) || app.FirstName.ToLower()
.Contains(name.ToLower()))
.GroupBy(app => new { app.TRN, app })
.Select(x => x.Key.app)
.ToListAsync()
.ConfigureAwait(false);
}
上述GroupBy 表达式在VS Studio 中编译失败。我的目标是按包含用户给定字符串的名称运行查询过滤结果,然后它应该按类似的TRN 数字对结果进行分组,返回这些应用程序的列表以返回视图。我想我真的很接近,但似乎无法弄清楚查询的最后一点。任何指导表示赞赏。
出现错误
InvalidOperationException: The LINQ expression 'DbSet<Application>
.Where(a => a.LastName.ToLower().Contains(__ToLower_0) || a.FirstName.ToLower().Contains(__ToLower_0))
.GroupBy(
source: a => new {
TRN = a.TRN,
app = a
},
keySelector: a => a)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()
更新
似乎这肯定是由于最近更新以来 .net core 3.x 和 EF core 如何协同工作发生了变化。我不得不使用AsEnumerable() 而不是ToListAsync() 将其更改为客户评估。 Steve py 给出的其余查询使用此方法。即使在阅读文档之后,我也不知道 groupby 在 LINQ 中是如何真正工作的,所以这对我有很大帮助。但是,将查询带到客户端 eval 可能会出现性能问题。
【问题讨论】:
-
编译时或运行时错误?突出显示哪一行?也许将
.GroupBy(app => new { app.TRN, app })更改为.GroupBy(app => app.TRN)? -
@JohnyL 我将错误添加到问题中作为编辑。我确实尝试过,但我需要查询的输出格式为
List<Application> -
将
.GroupBy(app => new { app.TRN, app })更改为.GroupBy(app => app.TRN)有帮助吗? -
不,不幸的是,它仍然没有给我正确的结果集。嗯,也许我应该以不同的方式解决这个问题。我想按 TRN 分组,这是一组重复的数字,例如 12345,在 Application 表中可能有许多具有相同序列的记录,我只想要每组 TRN 序列中的最新行。因此,如果该表有 3 行带有该 TRN,我只希望返回最后插入的行。这就是我试图为每组不同的 TRN 数字实现的目标
-
我回滚了您的上一个修订版,因为它会将问题更改为一个新问题,它不尊重现有答案。
标签: entity-framework entity-framework-6 ef-core-3.0 .net-core-3.1