Entity Framework Core with linq不翻译in查询中的enum



我尝试在枚举类型TypeDocument的where子句中进行查询,它不起作用,因为它看起来像linq表达式不能翻译为SQL查询。如果我理解正确的话,Linq不能将枚举转换为int进行比较:

documents.Where(doc => query.TypesExclus.Any(type => type != doc.TypeDocument))

我知道我可以在之前和之后做一个.ToListAsync(),但我更喜欢让数据库服务器处理过滤器以获得更好的性能。

我已经尝试添加值转换,但这并没有改变结果。https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions?tabs=data-annotations

我得到以下错误:

系统。InvalidOperationException: LINQ表达式'type =>(int)type == (int)EntityShaperExpression:
Sp.Domain.Entities.DocumentValueBufferExpression:ProjectionBindingExpression:外IsNullable:假无法翻译. typedocument。要么以可翻译的形式重写查询,要么通过插入对'AsEnumerable', 'AsAsyncEnumerable', 'ToList'或'ToListAsync'的调用显式切换到客户端求值。

代码:

public async Task<GetDocumentsResult> RetrieveAsync(GetDocumentRegimeQuery query)
{
var documents = context.Documents
.AsNoTracking()
.Where(doc => doc.Regime.Id == query.RegimeId
&& doc.AfficherSiteParticipant == true)
.Select(d => new DocumentDto { Id = d.Id, Nom = d.Nom, TypeDocument = d.TypeDocument, DateSauvegarde = d.DateSauvegarde, Extension = d.Extension });
if (query.TypesExclus.Any())
{
documents = documents.Where(doc => query.TypesExclus.Any(type => type != doc.TypeDocument));
}
return new GetDocumentsResult { Documents = await documents.ToListAsync() };
}

Entity Framework Core不支持将枚举类型转换为SQL。

在执行比较操作之前,可以尝试将枚举转换为整数。

documents = documents.Where(doc => query.TypesExclus.Any(type => (int)type != (int)doc.TypeDocument));

最新更新