如何简化Where(e => e.prop1.contains()|| e.prop2.contains()|| ...)中的重复OR条件 [英] How to simplify repetitive OR condition in Where(e => e.prop1.contains() || e.prop2.contains() || ...)
本文介绍了如何简化Where(e => e.prop1.contains()|| e.prop2.contains()|| ...)中的重复OR条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有很多这样的代码:
IQueryable<MyEntity> query...
query.Where(e => EF.Functions.Like(e.Property1, pattern)
|| EF.Functions.Like(e.Property2, pattern)
|| EF.Functions.Like(e.Property3, pattern)
...);
如何简化它以将重复代码删除为类似这样的内容:
How can I simplify it to remove the repetitive code to something like this:
query.Where(Search(pattern, e => e.Property1, e => e.Property2, e => e.Property3));
或
query.Where(e => Search(pattern, e.Property1, e.Property2, e.Property3))
查询必须通过EF转换为SQL,因此where条件不能只是任何返回布尔值的函数.它必须是可翻译的Expression< Func< TEntity,bool>>
The query must be translated to SQL by EF, so the where condition can't be just any function that return boolean. It must be translatable Expression<Func<TEntity, bool>>
推荐答案
您可以将其重写以将所有属性组合到一个数组中,并检查是否匹配:
You can rewrite it to combine all the properties into an array and check that for a match:
query.Where(e =>
new[]{ e.Property1, e.Property2, e.Property3}
.Any(p => EF.Functions.Like(p, pattern) )
);
等效的SQL是:
WHERE EXISTS (SELECT 1
FROM (VALUES
(e.Property1),
(e.Property2),
(e.Property3)
) v(Prop)
WHERE v.Prop LIKE @pattern
)
等效的&&/AND
语义略有不同:
query.Where(e =>
new[]{ e.Property1, e.Property2, e.Property3}
.All(p => EF.Functions.Like(p, pattern) )
);
等效的SQL是双负数:
The equivalent SQL is a double-negative:
WHERE NOT EXISTS (SELECT 1
FROM (VALUES
(e.Property1),
(e.Property2),
(e.Property3)
) v(Prop)
WHERE v.Prop NOT LIKE @pattern
)
这篇关于如何简化Where(e => e.prop1.contains()|| e.prop2.contains()|| ...)中的重复OR条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文