如何使用表达式构建动态查询(IN子句)

时间:2014-08-03 16:07:16

标签: c# sql entity expression

我有

<!-- language: c# -->
   Expression<Func<TEntity, bool>> 

由属性

组成
  • StartDate datetime
  • EndDate datetime
  • ShowArticles bool
  • ShowMaterials bool
  • ShowProducts bool

我想构建动态查询,如下所示:

SELECT * FROM Docs
WHERE StartDate >= @StartDAte 
AND EndDate <= @EndDAte 
AND ArticleInternalType IN (1,2,3)

所有bool类型都被限制为复选框(已选中)。 如果用户取消选中复选框查询也应该更改。用户取消选中ShowMaterials复选框的示例:

SELECT * FROM Docs
WHERE StartDate >= @StartDate 
AND EndDate <= @EndDAte 
AND ArticleInternalType IN (1,3)

这个表达式给出了尴尬的结果

FilterExpression =
f => f.DocumentDate >= StartDate.Date && f.DocumentDate <= EndDate.Date
&& (
showArticles == true ? f.ArticleInternalType == 1 : f.ArticleInternalType == -1 ||
showMaterials == true ? f.ArticleInternalType == 0 : f.ArticleInternalType == -1 ||
showProducts == true ? f.ArticleInternalType == 2 : f.ArticleInternalType == -1
);  

以下是SQLProfiler的结果

WHERE 
([Extent1].[DocumentDate] >= @p__linq__0) AND ([Extent1].[DocumentDate] <= @p__linq__1) 
AND 
((CASE WHEN (1 = @p__linq__2) THEN 
        CASE WHEN (1 = [Extent1].[ArticleInternalType]) 
                THEN cast(1 as bit) 
             WHEN (1 <> [Extent1].[ArticleInternalType]) 
                THEN cast(0 as bit) 
        END 
        WHEN (1 = @p__linq__3) THEN 
        CASE WHEN (2 = [Extent1].[ArticleInternalType]) 
                THEN cast(1 as bit) 
            WHEN (2 <> [Extent1].[ArticleInternalType]) 
                THEN cast(0 as bit) 
        END 
        WHEN (1 = @p__linq__4) THEN 
        CASE WHEN (3 = [Extent1].[ArticleInternalType]) 
                THEN cast(1 as bit) 
            WHEN (3 <> [Extent1].[ArticleInternalType]) 
                THEN cast(0 as bit) 
        END 
    ELSE cast(0 as bit) 
END) = 1)

有人可以给我建议,怎么做?

1 个答案:

答案 0 :(得分:1)

您应该可以使用int类型列表

来执行此操作
var types = new List<int>();
if (showArticles) types.Add(1);
if (showMaterials) types.Add(0);
if (showProducts) types.Add(2);
FilterExpression = f => f.DocumentDate >= StartDate.Date
    && f.DocumentDate <= EndDate.Date
    && types.Contains(f. ArticleInternalType);

您还可以简化您所写的表达式:

FilterExpression =
f => f.DocumentDate >= StartDate.Date && f.DocumentDate <= EndDate.Date
&& (
    showArticles && f.ArticleInternalType == 1
||  showMaterials && f.ArticleInternalType == 0 
||  showProducts && f.ArticleInternalType == 2
);