c# - LINQ 中的对象引用错误

标签 c# asp.net-mvc-3 linq

我应用了以下代码:

var country = from cnty in this.GetAll<CompanyDefinition>().ToList()
   where cnty.IsImported = true
   select new { 
      CompanyDefinitionID = cnty.CompanyDefinitionID
      , CompanyDefinitionName = cnty.Company.CompanyName + "(" + cnty.Country.CountryCode + "," + cnty.NaicsCode.NaicsCode1 + ")"
};

我收到对象引用错误。它指向“选择新”。正确的做法是什么?

最佳答案

问题是 CompanyCountryNaicsCodenull,您需要在尝试之前检查一下访问他们的属性。例如,您可以将查询重写为:

var country = from cnty in this.GetAll<CompanyDefinition>()
              where cnty.IsImported && cnty.Company != null && cnty.Country != null && cnty.NaicsCode != null
              select new {
                  ...
              }

关于c# - LINQ 中的对象引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12111049/

相关文章:

C#:保护级别错误

c# - 使用 Ninject 内核作为工作单元对象工厂

c# - Linq 查询仅在以点表示法编写时才有效

asp.net-mvc - 向 Sharp Architecture 注册自定义模型绑定(bind)器

c# - 通过引用传递引用

c# - 自动化测试期间的 WPF 组件资源

javascript - ASP.NET MVC Javascript 重定向编码问题

c# - 将字典转换为列表<struct>

linq - NHibernate:QueryOver<> 帮助

linq - F# 中的 EBay OData 类型提供程序并且使用 LINQ 没有得到任何结果