Reputation: 781
Coding up a statistics page for my website. I am using Linq with entity framework. I have a couple queries that work, but can't handle null exceptions. Just wondering if there is a way around it without having to readjust coding approach.
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;
This throws a null error because there is nothing to select with this where clause, but I will be needing this query for future purposes because eventually it will be used.
Cheers
Upvotes: 0
Views: 133
Reputation: 101681
Maybe you want something like this:
if(otherCount != null)
ViewBag.otherCount = otherCount.Count;
else ViewBag.otherCount = 0;
Select
or Where
will not throw a NullReferenceException
if you don't try to access a property or method of null object in the query.Your problem is about the last line.
Also you can simplify your code using FirstOrDefault
with a predicate:
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;
Upvotes: 2