Barry Dysert
Barry Dysert

Reputation: 705

I'm getting a null reference exception when Dapper tries to read a null database field. What to do?

I'm using C#.Net and the latest version of Dapper. I just started getting a null reference exception when Dapper reads a record from the database, but the field that it's trying to retrieve is null. What can I do about it?

What follows is what I think is the pertinent code:

        using (DapperInit.conn)
        {
            try
            {
                ProjectRollup projectRollup = new ProjectRollup();

                // get the Jobs in this Project
                string sql = "select JobID, JobName, TaxRate, ScheduledStart from [Jobs] where ProjectID = @ProjectID";
                IEnumerable<JobForRollup> jobs = DapperInit.conn.Query<JobForRollup>(sql, new { ProjectID = projID });

                // get the Discount rate for the project
                sql = "select Discount from [Projects] where ProjectID = @ProjectID";
                projectRollup.Discount = DapperInit.conn.Query<int>(sql, new { ProjectID = projID }).FirstOrDefault();

Here's what the ProjectRollup class looks like (if it matters):

public class WorkItemForRollup
{
    public Guid TaskID { get; set; }
    public string Description { get; set; }
    public bool Taxable { get; set; }
    public decimal Price { get; set; }
    public DateTime ScheduledDate { get; set; }
}

public class JobForRollup
{
    public Guid JobID { get; set; }
    public string JobName { get; set; }
    public decimal TaxRate { get; set; }
    public decimal Price { get; set; }
    public DateTime ScheduledStart { get; set; }
    public List<WorkItemForRollup> WorkItems { get; set; } = new List<WorkItemForRollup>();
}

public class ProjectRollup
{
    public decimal Total { get; set; }
    public int Discount { get; set; }
    public List<JobForRollup> Jobs { get; set; } = new List<JobForRollup>();
}

I'm successfully getting the jobs data from Dapper, and there is a record such that my ProjectID = projID, but the Discount field happens to be null. What can I do to prevent getting the null reference exception, because Discount is a nullable field? (Btw, it doesn't matter if I declare Discount to be int? - I still get the exception.)

Upvotes: 0

Views: 1915

Answers (1)

Barry Dysert
Barry Dysert

Reputation: 705

I just got it! I need to declare Discount to be an int? and I also need to tell Dapper that the datatype is int?. The offending line of code, therefore, must be:

                int? discount = DapperInit.conn.Query<int?>(sql, new { ProjectID = projID }).FirstOrDefault();

It works!

Upvotes: 4

Related Questions