C# Linq不能为Null查询不返回任何记录时引发错误
我有以下疑问:C# Linq不能为Null查询不返回任何记录时引发错误,c#,linq,asp.net-mvc-4,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(); List formulasInCat=new List(); produ
List<Models.PricingFormula> formulasInCat = new List<Models.PricingFormula>();
productsInCat = (from x in Model.PPPVMs
where x.CategoryId == category.ProductCategoryId select x).ToList();
List formulasInCat=new List();
productsInCat=(从Model.PPPVMs中的x开始)
其中x.CategoryId==category.ProductCategoryId选择x).ToList();
查询未返回任何记录,我得到的错误是:
值不能为null
处理此问题的正确方法是什么?在调用
ToList()
方法之前,可以使用DefaultIfEmpty()
。如果Model
或category
为空,则会出现NullReferenceException
值不能为null
是ArgumentNullException
的消息,这意味着PPPVMs很可能为null
List<Models.PricingFormula> productsInCat;
if (Model.PPPVMs == null)
productsInCat = new List<Models.PricingFormula>();
else
productsInCat = (from x in Model.PPPVMs
where x.CategoryId == category.ProductCategoryId select x).ToList();
列出产品目录;
如果(Model.PPPVMs==null)
productsInCat=新列表();
其他的
productsInCat=(从Model.PPPVMs中的x开始)
其中x.CategoryId==category.ProductCategoryId选择x).ToList();
您确定型号和类别不为空吗?谢谢。模型和类别都不为null。@它在查询的哪一部分抛出该值?您是否初始化了Model.PPPVMs?从异常中查看stacktrace会有帮助。PPVM代表什么?