user777310
user777310

Reputation: 215

Checking null in LinQ

This is my query:

var entityMerchantVisit =
     from e in context.MerchantCustomerVisit
     where e.CustomerId == currentCustGuid
     group e by  
           new { e.Merchant.Locations.FirstOrDefault().CityId } into mcvGroup
     orderby mcvGroup.Count() descending
     select mcvGroup;

I'm getting error

"The cast to value type 'Int32' failed because the materialized value is null" when e.Merchant.Locations.FirstOrDefault().CityId is null.

How do I check if it's null before hand. I would like to assign it as (int) 0 , if it is null.

Upvotes: 1

Views: 9276

Answers (4)

gideon
gideon

Reputation: 19465

Something like this could work:

var entityMerchantVisit =
     from e in context.MerchantCustomerVisit
     where e.CustomerId == currentCustGuid
     group e by  
           new { e.Merchant.Locations.FirstorDefault() != null 
                  ? e.Merchant.Locations.First().CityId : 0
               } into mcvGroup
     orderby mcvGroup.Count() descending
     select mcvGroup;

Based on your comment you could maybe try the following (note the parenthesis) :

     group e by  
           new { CityID = ((int)e.Merchant.Locations.FirstorDefault() != null 
                  ? e.Merchant.Locations.First().CityId : 0)
               } into mcvGroup
     orderby mcvGroup.Count() descending

Upvotes: 4

Ben
Ben

Reputation: 6059

You can use the let syntax to bind e.Merchant.Locations.FirstOrDefault() to a range variable, and then check that for null. This lets you conveniently identify merchants without locations, and gives you a concise ternary-operator expression to boot.

var entityMerchantVisit =
     from e in context.MerchantCustomerVisit
     where e.CustomerId == currentCustGuid
     let location = e.Merchant.Locations.FirstOrDefault()
     group e by  
           new { CityId = (location == null ? 0 : location.CityId) } into mcvGroup
     orderby mcvGroup.Count() descending
     select mcvGroup;

Upvotes: 4

devgeezer
devgeezer

Reputation: 4189

You could try using a Nullable<int> expression:

var entityMerchantVisit =
    from e in context.MerchantCustomerVisit
    where e.CustomerId == currentCustGuid
    group e by new {
        CityId = e.Merchant.Locations.Any() ? 
            e.Merchant.Locations.First().CityId
            : default(int?)
    } into mcvGroup
    orderby mcvGroup.Count() descending
    select mcvGroup;

Upvotes: 0

Alan
Alan

Reputation: 46813

Use the null coalescing operator (??)

var entityMerchantVisit =
 from e in context.MerchantCustomerVisit
 where e.CustomerId == currentCustGuid
 group e by  
       new { (e.Merchant.Locations.FirstOrDefault().CityId ?? 0) } into mcvGroup
 orderby mcvGroup.Count() descending
 select mcvGroup;

Upvotes: 0

Related Questions