我想从sqlite数据库中获取项目(数据库中有大约6,000个项目)
有些项目是重复的因此,我想在获取项目时删除这些重复信息
我使用了以下代码
public async static Task<List<myModel>> GetAllItems()
{
using var db = new dbContext();
var query =
from item in db.myTable.GroupBy(x => x.Id).Select(x => x.First())
select new myModel
{
Id = item.Id,
Name = item.Name,
...
};
return await query.ToListAsync();
}
但我收到以下错误
System.InvalidOperationException: 'The LINQ expression 'GroupByShaperExpression:
KeySelector: m.Id,
ElementSelector:EntityShaperExpression:
EntityType: myTable
ValueBufferExpression:
ProjectionBindingExpression: EmptyProjectionMember
IsNullable: False
.First()' 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 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'
更新(EF Core 6.0):
EF Core 6.0 确实添加了对一些额外运算符的支持GroupBy
结果集,包括有问题的结果集,因此现在原始 LINQ 查询应该完好无损。
原来的:
由于目前(希望 v6.0 会添加一些)EF Core 不支持GroupBy
除了键/聚合投影之外的结果运算符,它不能用于实现每组前 N 个项目函数,这就是你基本上想要做的(对于N == 1
).
因此,作为一种解决方法(无需第三方扩展),您必须通过以下方式手动执行此操作:(1) 使用子查询来选择唯一键,然后 (2) 将其用作相关限制子查询的过滤器。例如就像是
var query = db.myTable.Select(x => new { x.Id }).Distinct() // (1)
.SelectMany(key => db.myTable.Where(x => x.Id == key.Id).Take(1)) // (2)
// The rest is the same as the original
.Select(item => new myModel
{
Id = item.Id,
Name = item.Name,
...
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)