我正试图使用SomeModel的IEnumerable的请求来过滤这种伪结构的实体(字段1、字段2、字段3(的dbset,其中SomeModel包含对(字段1和字段2((相同的字段子集(
我试过
var ordersList3 = await _dbContext.MyEntities.
AsNoTracking().
Where(a => request.Contains(new SomeModel() { field1 = a.field1, field2 = a.field2})).
ToListAsync();
但不起作用
你能建议一下通过包含字段子集的模型列表过滤dbset的正确方法吗?
我不知道这在您的情况下是否必要,但有时您需要直接写下表达式。因为这可能有点有趣,给你:
public static Expression<Func<PseudoStructure, bool>> GetPredicate<PseudoStructure>(
IEnumerable<PseudoStructure> request) {
var parameter = Expression.Parameter(typeof(PseudoStructure), "o");
var expression = request.Aggregate(
(Expression)null,
(acc, next) => MakeBinary(
acc,
CompareInstances(parameter, next),
ExpressionType.Or));
return Expression.Lambda<Func<PseudoStructure, bool>>(expression, parameter);
}
此方法生成表达式<Func<伪结构,bool>gt;它由检查实例相等性的表达式组成:
private static Expression CompareInstances<PseudoStructure>(
ParameterExpression parameter,
PseudoStructure constant)
=> typeof(PseudoStructure)
.GetFields()
.Select(fieldInfo => Expression.Equal(
Expression.Constant(fieldInfo.GetValue(constant)),
Expression.Field(parameter, fieldInfo)))
.Aggregate(
(Expression)null,
(expression, binaryExpression) => MakeBinary(expression, binaryExpression, ExpressionType.And)
);
}
}
请注意,相等意味着字段值相等。MakeBinary是Expression.MakeBinary:的一个简单包装器
private static Expression MakeBinary(Expression left, Expression right, ExpressionType expressionType)
=> left == null || right == null ?
left ?? right
: Expression.MakeBinary(expressionType, left, right);
你可以这样使用:
public struct Foo
{
public int A;
public decimal B;
public decimal C;
}
var values = new List<Foo> {
new Foo {A = 1, B = 2, C = 3},
new Foo {A = 4, B = 5, C = 6},
new Foo {A = 7, B = 8, C = 9},
new Foo {A = 10, B = 11, C = 12}
};
var expression =
GetPredicate(new[] {
new Foo {A = 1, B = 2, C = 3},
new Foo {A = 10, B = 11, C = 12}
});
var result = values.AsQueryable().Where(expression).ToList();