c# - 管理空/空列表
问题描述
我正在用 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();
}
}
解决方案
推荐阅读
- testing - RxJs Marble 使用 withLatestFrom 测试 concatMap
- java - 错误:找不到符号 BitmapTransformation/BitmapPool
- javascript - 如何使用 XSLT 从 url 显示 XML 数据
- java - Firebase setValue() 调用上 java.util.HashMap$HashIterator 的 StackOverflowError
- elm - Cmd.map 是将 Elm SPA 拆分为模块的正确方法吗?
- r - geom_bar 和 geom_linerange 之间的技术差异
- javascript - JSON对象的逆时间顺序
- mysql - AWS RDS MySQL innodb/btr_search_latch
- r - 为什么我的自定义二项式函数会给我一个 $Inf$ 作为回报?
- python - pathlib 和字符串连接的控制顺序