首页 > 解决方案 > 管理空/空列表

问题描述

我正在用 Asp Core 3.1 开发一个 webapi。我有这样的课:

public class Employee
{
    public string name { get; set; }
    public string surname { get; set; }
    public List<Contact> contacts { get; set; }
}

在 EmployeeController 中的 Get 操作中,我正在做这样的事情:

var emp = new DTO.EmployeeDetails();
emp = await getEmployeeBaseData(id);

if (emp == null)
    return NotFound();

emp.contacs = await getContats(id);

当员工没有联系人时,问题就来了:

System.NullReferenceException:对象引用未设置为对象的实例。

我尝试像这样初始化列表:

emp.contacs = new List<Contact>();
emp.contacs = await getContats(id);

唯一真正有效的是:

try
{
    emp.contacs = await getContats(id);
}
catch (NullReferenceException)
{
    Console.WriteLine("No contacs for id: " + id);
}

这是非常丑陋的。

我不能将 null 分配给列表。我不能分配一个空的枚举。我能做些什么?

编辑:对不起,如果我写的问题太抽象或笼统。这是 getcontacts 方法:

private async Task<List<Contact>> getContats(int? id)
{
    return await DAL.DataAccess.LoadDataAsync<Contact>(_ConnString,
        "SELECT * FROM contacs WHERE id = @id",
        new { id = id });
}

这是其中使用的 LoadDataAsync(这是一个使用 Dapper 的简单 DAL):

public static async Task<List<T>> LoadDataAsync<T>(string conn, string sql, T data)
{
    using (IDbConnection cn = new SqlConnection(conn))
    {
        cn.Open();
        var res = await cn.QueryAsync<T>(sql, data);
        return res.ToList();
    }
}

标签: c#asp.net-corenullreferenceexceptionwebapi

解决方案


推荐阅读