当我有2个where()时MVC IEnumable toList没有返回结果

时间:2015-07-29 23:33:44

标签: c# asp.net-mvc linq entity-framework ienumerable

当我有1个过滤器时,我的代码工作正常但是当我有2个过滤器时,ToList()不返回任何行。我尝试运行代码生成的SQL,SQL确实返回了一些东西。

IEnumerable<Tag> tags = db.Tags;

if( ID != "")
    tags = tags.Where(t => t.ID == ID);

if( part != "")
    tags = tags.Where(t => t.PartNumber == part);

tags.OrderBy(t => t.ID);
tags = tags.Skip(PageIndex * PageSize).Take(PageSize);

return View(tags.ToList());

当两个过滤器都存在时,将返回0行。

输出SQL:

SELECT TOP (10)
  [Project1].[ID] AS [ID],
  [Project1].[PartNumber] AS [PartNumber]
FROM (SELECT
  [Project1].[ID] AS [ID],
  [Project1].[PartNumber] AS [PartNumber],
  ROW_NUMBER() OVER (ORDER BY [Project1].[ID] DESC) AS [row_number]
FROM (SELECT
  [Extent1].[ID] AS [ID],
  [Extent1].[PartNumber] AS [PartNumber]
FROM [Tag] AS [Extent1]
WHERE ([Extent1].[ID] = @p__linq__0)
AND ([Extent1].[PartNumber] = @p__linq__1)) AS [Project1]) AS [Project1]
WHERE [Project1].[row_number] > 0
ORDER BY [Project1].[ID] DESC

1 个答案:

答案 0 :(得分:2)

那是因为您已经过滤了您的列表。

执行此操作时:

tags = tags.Where(t => t.ID == ID);

您的代码集已更新,现在包含基于过滤器的列表。

当您随后执行此操作时:

tags = tags.Where(t => t.PartNumber == part);

除非您的标签具有给定的ID和PartNumber,否则不会返回任何内容。

如果要构建条件过滤器,可以执行以下操作:

var query = tags.AsQueryable();

if(ID != "")
    query = query.Where(w => w.ID == ID);

// add second filter
if( part != "")
    query = query.Where(w => w.PartNumber == part);

return query.ToList();