c# - 空 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
解决方案
这不是您的答案,但您尝试在 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();
推荐阅读
- python - 慢速打印 打印前等待时间过长
- c - 如何以动态排列的结构加载二进制文件的信息?
- javascript - 如何使用 JavaScript 或 jQuery 将一些文本插入到 textarea 中?
- reactjs - 如何防止用户多次单击登录表单的提交按钮错误反应?
- python - 超过行长时缩进
- r - 合并 R 中的列时的动态列名
- javascript - Cloudfront 和 Lambda@Edge:删除响应标头
- java - Gradle sourceSets: classesDir 已被弃用
- ios - 使用 xcode 和 swift 从照片库中选择要显示到 Apple Watch 上的图像视图的图像
- visual-c++ - 如果它是私有的,如何访问派生类