为我的网站编制统计页面。我正在使用Linq实体框架。我有几个查询可以工作,但无法处理null异常。只是想知道是否有办法绕过它而不必重新调整编码方法。
var countriesElse = db.Profiles
.GroupBy(av => av.Country)
.Select(g => new { Country = g.Key, Count = g.Count() });
var otherCount = countriesElse
.Where(x => x.Country != "US" && x.Country != "CA").FirstOrDefault();
ViewBag.otherCount = otherCount.Count;
这会抛出一个null错误,因为没有什么可以用这个where子句选择,但是我将需要这个查询用于将来的目的,因为它最终会被使用。
干杯
答案 0 :(得分:2)
也许你想要这样的东西:
if(otherCount != null)
ViewBag.otherCount = otherCount.Count;
else ViewBag.otherCount = 0;
如果您不尝试在查询中访问 null 对象的属性或方法, Select
或Where
将不会抛出NullReferenceException
。您的问题是关于最后一行。
此外,您可以使用带有谓词的FirstOrDefault
来简化代码:
var profile = db.Profiles
.GroupBy(av => av.Country)
.Select(g => new { Country = g.Key, Count = g.Count() })
.FirstOrDefault(x => x.Country != "US" && x.Country != "CA");
ViewBag.otherCount = profile== null ? 0 : profile.Count;