我们正在使用
我想要实现的是,在属性上应用
我有以下代码:
但是这样调用并不可行,因为它需要对所有实体都通用。 (我们根据 Datatables 中筛选的列将这些
System.Linq.Expressions.Expression
来构建自定义表达式,这些表达式被应用于IQueryable
的.Where()
中。我想要实现的是,在属性上应用
.HasFlag()
方法(在EF 6.1中引入),然后将其用于.Where()
表达式中。我有以下代码:
var memberExpression = propertyExpression as MemberExpression;
var targetType = memberExpression?.Type ?? typeof(decimal?);
var value = Enum.Parse(type, searchValue);
var hasFlagMethod = targetType.GetMethod(nameof(Enum.HasFlag));
var hasFlagExpression = Expression.Call(propertyExpression, hasFlagMethod, Expression.Convert(Expression.Constant(value), typeof(Enum)));
propertyExpression
的值显示为{x.Type}
,而hasFlagMethod
被显示为{Boolean HasFlag(System.Enum)}
,两者看起来都很不错。
hasFlagExpression
的值为{x.Type.HasFlag(Convert(Foo))}
,这也看起来完全没问题,除了Convert(Foo)
这一部分,但这样做是必要的,否则我将得到另一个异常,即指定的参数类型不能应用于此方法,因为它不是System.Enum
。
当我们使用.Where()
枚举IQueryable
时,会出现以下异常:
NotSupportedException: LINQ to Entities does not recognize the method
'Boolean HasFlag(System.Enum)' method, and this method cannot
be translated into a store expression.
直接在 IQueryable
上调用它是有效的(我们也使用 EF 6.1,它添加了对 Enum.HasFlag()
的支持),如下所示:
Entities.Where(x => x.Type.HasFlag(BarEnum.Foo));
但是这样调用并不可行,因为它需要对所有实体都通用。 (我们根据 Datatables 中筛选的列将这些
.Where()
条件组合在一起)