c# - 当查询没有返回记录时,会抛出 Linq Cannot be Null 错误

标签 c# linq asp.net-mvc-4 null

我有以下查询:

List<Models.PricingFormula> formulasInCat = new List<Models.PricingFormula>();
productsInCat = (from x in Model.PPPVMs 
    where x.CategoryId == category.ProductCategoryId select x).ToList();

查询没有返回任何记录,我得到的错误是:

Value cannot be null.

处理这个问题的正确方法是什么?

最佳答案

您可以在调用 ToList() 方法之前使用 DefaultIfEmpty()

关于c# - 当查询没有返回记录时,会抛出 Linq Cannot be Null 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16869473/

相关文章:

.net - Global.asax ASP.Net Web API 中的 GlobalConfiguration.Configuration.EnsureInitialized() 是什么

c# - MVC 中具有相同签名的方法

c# - CompareTo 方法不起作用,它不会从 Album 类中获取 AlbumName - 我认为是 IComparable 问题

c# - MVC 最大请求长度超出异常 - 调用其他 Controller 操作

C#按优先级获取第一个非空属性

c# - 在单个 LINQ 表达式中嵌入 null 测试

c# - Visual Studio 2012 RC 中不显示重构菜单

python - LINQ OfType<T>() 的 Python 等效项是什么(在 .NET 中)

c# - Entity Framework 6 过滤子对象

ajax - 通过 ajax 动态添加项目到模型中的列表