首页 > 解决方案 > 空 linq 查询结果异常

问题描述

我正在尝试向我的 MVC 应用程序添加过滤器。我在这方面有点成功,因为如果它存在于数据库中,我可以返回一个过滤值。

但是,当它不存在于数据库中时,我希望它返回一个空列表。因为如果结果为零,Linq 应该返回空。但是,如果由于某种原因代码语句失败,并且输入的字段与任何 db 条目不匹配,则我使用 try catch 捕获任何异常,则 linq 查询中断为 catch 并且异常为空。

我不知道出了什么问题,它甚至不应该被抓住。

林克查询:

 if (attr1 == "null" && attr3 != "null" && attr2 != "null")
    {
       attr1 = "%";

         Size = db.GetFilterResultCount(index, Size, attr1, attr2, attr3).Count();
         accountlist = db.GetFilterResult(index, Size, attr1, attr2, attr3).ToList();

         filteredlist.GetList = accountlist;
         filteredlist.index = index;
         filteredlist.size = Size;
         filteredlist.totalSize = db.Accounts.Count();
         filteredlist.resultSize = db.GetFilterResultCount(index, Size, attr1, attr2, attr3).Count();
    }

这是我用来检查哪个字段被过滤的众多条件之一。但是 linq 查询对所有人来说都是一样的。

存储过程:

    CREATE PROCEDURE [dbo].[GetFilterResult]
@PageIndex INT,  
@pageSize INT,
@attr1 nvarchar(300),
@attr2 nvarchar(300),
@attr3 nvarchar(300)

    AS
    Begin
    SELECT  Accounts.firstName, Accounts.lastName, Accounts.Email, 
     Accounts.dateOfBirth, Accounts.phoneNo, Countries.CountryName 

    FROM Accounts INNER JOIN Countries On Accounts.CountryID = 
     Countries.CountryID

    Where (Accounts.firstName LIKE CONCAT('%', @attr1, '%') and 
     Accounts.lastName LIKE CONCAT('%', @attr2, '%') and Accounts.CountryID 
      Like CONCAT('%', @attr3, '%')) 

    ORDER BY UserId OFFSET @PageSize*(@PageIndex-1) ROWS FETCH NEXT 
     @PageSize ROWS ONLY;

    END

GetFilterResultCount:

   CREATE PROCEDURE [dbo].[GetFilterResult]
@PageIndex INT,  
@pageSize INT,
@attr1 nvarchar(300),
@attr2 nvarchar(300),
@attr3 nvarchar(300)

    AS
    Begin
    SELECT  Accounts.firstName, Accounts.lastName, Accounts.Email, 
     Accounts.dateOfBirth, Accounts.phoneNo, Countries.CountryName 

    FROM Accounts INNER JOIN Countries On Accounts.CountryID = 
     Countries.CountryID

    Where (Accounts.firstName LIKE CONCAT('%', @attr1, '%') and 
     Accounts.lastName LIKE CONCAT('%', @attr2, '%') and Accounts.CountryID 
      Like CONCAT('%', @attr3, '%')) 


    END

标签: c#mysqlasp.net-mvclinq

解决方案


这不是您的答案,但您尝试在 attr1 == "null" 时忽略 attr1 where 子句。您可以在查询中使用 IFNULL 函数

Where (Accounts.firstName LIKE  CONCAT('%', IFNULL(@attr1, Accounts.firstName), '%') and

并将 null 传递给存储过程

   attr1 = null;
   accountlist = db.GetFilterResult(index, Size, attr1, attr2, attr3).ToList();

推荐阅读