KTLind
KTLind

Reputation: 147

object reference error in LINQ query

var query1 = from a in inputDataRecords
             from b in employeeDataRecords
                  .Where(badgeNumber => a.Responsi == badgeNumber.Badge)
                  .Where(badgeNumber => a.Auth == badgeNumber.Badge)
                  .Where(badgeNumber => a.ByN == badgeNumber.Badge)
                  .DefaultIfEmpty()
                  select new {a,
                              responsibleName = b.EmployeeName,
                              authName = b.EmployeeName,
                              createName = b.EmployeeName};

gives me an error of: Object reference not set to an instance of an object. I know it's because I'm not referencing b.

But changing the select to:

select new {a, b,
            responsibleName = b.EmployeeName,
            authName = b.EmployeeName,
            createName = b.EmployeeName};

doesn't help. QuickWatch on query1 shows that b is null.

Upvotes: 0

Views: 329

Answers (2)

David
David

Reputation: 10708

note that you're using a number of items from .Where clauses, which could be null in the collection and thus throw this exception from any one of those lambdas. Try using a .Where(o => o != null) on both of those collections, and that may clear up the error.

Upvotes: 0

Servy
Servy

Reputation: 203802

b is null beacuse you specifically called out in your query that b should be null if the sequence is empty through your use of DefaultIfEmpty. If you don't want to have a null b item when that sequence is empty, omit that operation. If you do, then you need to support having a null b value in your query.

Upvotes: 2

Related Questions