当Dapper尝试读取一个空数据库字段时,我收到一个空引用异常。该怎么办?

时间:2018-11-16 19:58:07

标签: c# nullreferenceexception dapper

我正在使用C#.Net和最新版本的Dapper。当Dapper从数据库中读取一条记录时,我刚刚开始获得null引用异常,但是它试图检索的字段为null。我该怎么办?

接下来是我认为的相关代码:

        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();

这是ProjectRollup类的外观(如果重要的话):

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>();
}

我已经从Dapper成功获取了jobs数据,并且有一条记录记录了我的ProjectID = projID,但是Discount字段恰好为空。由于Discount是一个可为空的字段,我该怎么办以防止出现空引用异常? (顺便说一句,我是否将Discount声明为int?都没关系-我仍然会遇到异常。)

1 个答案:

答案 0 :(得分:1)

我知道了!我需要声明Discountint? ,并且我还需要告诉Dapper,数据类型为int?。因此,令人反感的代码行必须为:

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

有效!