繁体   English   中英

具有 linq 的 Entity Framework Core 不会在 in 查询中转换枚举

[英]Entity Framework Core with linq does not translate enum in a in query

我尝试在枚举类型为TypeDocument的 where 子句中执行 in 查询,但它不起作用,因为它看起来像 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

我收到以下错误:

System.InvalidOperationException: LINQ 表达式 'type => (int)type == (int)EntityShaperExpression:
Sp.Domain.Entities.Document ValueBufferExpression: ProjectionBindingExpression: Outer IsNullable: False.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。

在执行比较之前,您可以尝试将枚举转换为 integer。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM