I’m using Dapper to pull a list of Employee objects with their emails, which are stored in another table. I’m getting an error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'


When I hover over “employee”, I see it has pulled the correct information. When I hover over email, I see it has pulled the correct information. Where is the problem? I’ve been working on this for days and can’t get my head around the issue.
Here’s the code:

public async Task<List<EmployeeModel>> TestFunction()
        {
            using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString("WorkDeskDB")))
            {

                var sql = @"Select e.id, e.FirstName, e.LastName, em.EmployeeID, em.id, em.Address, em.Type 
                            From Employees e
                            Inner Join Email em
                            On em.EmployeeID = e.id";

                var employees = await connection.QueryAsync<EmployeeModel, EmailModel, EmployeeModel>(sql, (employee, email) =>
                {
                    employee.Email.Add(email);
                    return employee;
                }, splitOn: "EmployeeID");

                var result = employees.GroupBy(e => e.ID).Select(g =>
                  {
                      var groupedEmployee = g.First();
                      groupedEmployee.Email = g.Select(e => e.Email.Single()).ToList();
                      return groupedEmployee;
                  });
                return (List<EmployeeModel>)result;
            }
        }

Haven’t you posted this already? The problem is that on your EmployeeModel object, Email is a null List when you’re calling .Add() on it. You need to either check if it’s null and initialize it before calling .Add() or on your model object you can give it a default value of an empty initialized

I posted it in another group but wasn’t able to implement the offered solutions successfully. It was because because, as chrisoverzero pointed out, I was casting my result incorrectly. The solutions offered, turns out, were on point, but I was partly asking the wrong question.
employee.Email is probably null. Might want to add the coalescence operator (employee?.Add) if you’re fine not adding the email of the employee doesn’t have one Which line, exactly, throws the NullReferenceException?


I would guess that the property Email of the type EmployeeModel is null. I have to guess, though, because you haven’t given us enough to go on. Does its definition look like this?
If so, do one of these instead:
…unless you want to leave it null, in which case, do as /u/TheBrownJohnBrown suggested. (But you shouldn’t want to have collection types be null.)


(Unrelatedly, the cast on the final line will always fail. result is an IEnumerable<EmployeeModel> as implemented by some type which isn’t a List<EmployeeModel> – you’ll want ToList() instead.)
Thanks for the reply! Actually, the definition is this:
EmailModel takes Type and Address as properties. I’ve added the initialization, so now it reads:


I also changed the cast to ToList, and everything is working great. Thanks so much for your help! Incidentally, although I followed your instructions and made it work, I’m still confused by the whole concept. If you get a moment, could you explain it to me like I’m four years old? Or twelve, maybe.
Fixed formatting.
Hello, chrisoverzero: code blocks using triple backticks (“`) don’t work on all versions of Reddit!
Some users see this / this instead.
To fix this, indent every line with 4 spaces instead.

source