//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()
UPDATE看来这肯定是由于最近更新以来 .net core 3.x 和 EF core 一起运行的方式发生了变化。我必须使用以下方法将其更改为客户评估AsEnumerable()
代替ToListAsync()
。 Steve py 给出的其余查询适用于此方法。即使在阅读了文档之后,我也不知道 groupby 在 LINQ 中是如何工作的,所以这对我帮助很大。然而,将查询传递给客户端评估可能会产生性能问题。
EF core 中的 GroupBy 支持就是一个笑话。
这在 EF6 的服务器上完美运行
var nonUniqueGroups2 = db.Transactions.GroupBy(e => new { e.AccountId, e.OpeningDate })
.Where(grp => grp.Count() > 1).ToList();
在 EF core 中,它会导致异常“无法转换给定的 'GroupBy' 模式。在 'GroupBy' 之前调用 'AsEnumerable' 以在客户端对其进行评估。”消息有误导性,请勿致电AsEnumerable
因为这应该在服务器上处理。
我找到了解决方法here https://tipsfordev.com/groupby-can-t-be-translated。额外的Select
会有帮助的。
var nonUniqueGroups = db.Transactions.GroupBy(e => new { e.AccountId, e.OpeningDate })
.Select(x => new { x.Key, Count = x.Count() })
.Where(x => x.Count > 1)
.ToList();
该解决方法的缺点是结果集不包含组中的项目。
有一个EF核心issue https://github.com/dotnet/efcore/issues/17068#issuecomment-586464350。请对其进行投票,以便他们真正解决此问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)