MVC IEnumable toList返回没有结果,当我有2 where()
本文关键字:where 结果 toList IEnumable 返回 MVC | 更新日期: 2023-09-27 18:05:22
当我有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
那是因为你已经过滤了你的列表。
执行时:
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();