XRM where子句中的可空过滤器 [英] Nullable filters in XRM where clause
问题描述
我在WCF项目中使用XRM(早期绑定)类型,因此我可以访问CRM模型并可以使用LINQ查询.但是我一直在遇到
I'm using the XRM (early bound) types in a WCF project so I have access to the CRM model and can use LINQ queries. But I've been running into a problem described here, it's the limitations on the where
clause specific to XRM LINQ:
[条款限制]
子句的左侧必须是属性名称,而右侧 该子句必须是一个值.您不能将左侧设置为常数.两个都 子句的边不能是常量.
The left side of the clause must be an attribute name and the right side of the clause must be a value. You cannot set the left side to a constant. Both the sides of the clause cannot be constants.
支持包含,StartsWith,EndsWith和Equals的String函数.
Supports the String functions Contains, StartsWith, EndsWith, and Equals.
一个不断弹出的要求是当参数为null时,应返回所有实体,否则按该参数过滤.但是我想不出一种方法来打破要求上面的内容,或者编写多个查询以处理该情况为空的情况.
One requirement that keeps popping up is when a parameter is null, all entities should be returned otherwise filter by the parameter. But I can't think of a way to do this without breaking the requirements above, or writing multiple queries to handle the scenario when it's null.
这是我的一个查询的示例,typeFilter == null
是这里的问题,因为我在LHS上使用了常量.在我的真实代码中,有一个保护子句将typeFilter == null
指向另一个查询,但是我现在必须添加一个开始/结束日期过滤器(都可以为空),并且我无法表达我不想要的数量为空值的每种组合编写查询.
this is an example of one of my queries, the typeFilter == null
is the problem here is I've used a constant on the LHS. In my real code there's a guard clause that points typeFilter == null
to another query but I now have to add a start/end date filter (both nullable) and I cannot express how much I don't want to write a query for every combination of nullables.
private IQueryable<EventInfo> getAllEvents( DataContext context, EventType? typeFilter )
{
return (
from evt in context.new_eventSet
where
( evt.statecode == new_eventState.Active ) &&
( typeFilter == null || evt.new_EventType.Value == (int) typeFilter.Value )
select new EventInfo()
{
ID = evt.Id,
EventType = (EventType) evt.new_EventType.Value
...
} );
}
推荐答案
If you want to use the Linq syntax, it is possible to construct a query dynamically using LinqKit.
我已经在我目前正在从事的Dynamics CRM项目中将其用于此目的,并且它做得很好.
I have used it for this purpose on the Dynamics CRM project which I'm currently working on, and it does the job very well.
请参考以下答案,这是我的主意: https://stackoverflow.com/a/5152946/344988
Please refer to the following answer, which is where I got the idea: https://stackoverflow.com/a/5152946/344988
这篇关于XRM where子句中的可空过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!