linq 根据IQueryable中的多个枚举值检查值

hxzsmxv2  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(131)

我正在尝试编写一个优雅的解决方案,在一个IQueryable中针对多个枚举值过滤一个值。

分机号

public static class EnumExtensions
{
    public static bool IsAny<T>(this T value, params T[] choices)
    where T : Enum
    {
        return choices.Contains(value);
    }
}

用法

query = query.Where(x => x.Status.IsAny(OrderStatus.Accepted, OrderStatus.Received, OrderStatus.Approved));

但是当我执行这个命令时,我得到了以下错误:

An unhandled exception has occurred while executing the request.
System.InvalidOperationException: The LINQ expression 'DbSet<SalesOrder>
.Where(s => s.DeletedAt == null)
.Where(s => False || s.SellerId == __request_OwnerId_0)
.Where(s => s.Status
    .IsAny(OrderStatus[] { Accepted, Received, Approved, }))' 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(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

有什么建议吗?

31moq8wy

31moq8wy1#

你不能在Linq查询和EF的Expression<>参数中使用自定义方法。你需要用长格式的方法来实现:

query = query
    .Where( x =>
        x.Status == OrderStatus.Accepted ||
        x.Status == OrderStatus.Received ||
        x.Status == OrderStatus.Approved
    );

根据您的RDBMS,您 * 也许 * 可以这样做:

static readonly OrderStatus[] _these = new[] { OrderStatus.Accepted, OrderStatus.Received, OrderStatus.Approved };

// ...

query = query.Where( x => _these.Contains( x.Status ) );

...应转换为以下SQL:

WHERE
    x.Status IN ( 0, 1, 2 )

(假设OrderStatus.Accepted == 0Received == 1Approved == 2)。

相关问题