使用Web API向已有账户添加联系人时遇NullReferenceException异常
Web API写入数据时触发NullReferenceException异常
方法代码
[HttpPost] [Route("AddNewContactToExistingAccount")] public async Task<ActionResult<string>> AddNewContactToExistingAccount(string firstName, string secondName, string email) { //查找包含指定邮箱联系人的账户并添加新联系人 var ac = await _dataContext.Accounts.FirstOrDefaultAsync(x => x.Contacts.Any(y => y.Email == email)); if (ac==null) { return BadRequest("系统中无包含该邮箱的账户,请创建带新联系人的账户"); } var newContact = new Contact(); newContact.FirstName = firstName; newContact.SecondName = secondName; newContact.Email = email; ac.Contacts.Add(newContact); _dataContext.Contacts.Add(newContact); await _dataContext.SaveChangesAsync(); return Ok(""); }
数据库实体结构
public class Account { public int Id { get; set; } public string AccountName { get; set; } public List<Contact> Contacts { get; set; } } public class Contact { public int Id { get; set; } public string FirstName { get; set; } public string SecondName { get; set; } public string Email { get; set; } public int AccountId { get; set; } public Account Account { get; set; } }
异常信息
System.NullReferenceException: 对象引用未设置为对象的实例。
问题原因
异常出在ac.Contacts.Add(newContact),核心原因是ac.Contacts为null,具体有两个触发场景:
- EF Core默认不会自动加载导航属性,查询Account时未显式加载
Contacts集合,导致从数据库取出的Account对象中Contacts未初始化; - Account实体类未给Contacts集合设置默认初始化值,即便数据库中有关联数据,对象实例的Contacts仍会是null。
另外代码中_dataContext.Contacts.Add(newContact)属于冗余操作——通过ac.Contacts.Add关联后,EF会自动跟踪该Contact实体,无需手动添加到DbSet。
解决方案
方案1:初始化Account的Contacts集合
在Account类中直接给Contacts属性设置默认值,确保任何Account实例的Contacts都不为null:
public class Account { public int Id { get; set; } public string AccountName { get; set; } public List<Contact> Contacts { get; set; } = new List<Contact>(); }
方案2:查询时显式加载Contacts导航属性
使用Include方法强制EF加载Account关联的Contacts集合:
var ac = await _dataContext.Accounts .Include(x => x.Contacts) .FirstOrDefaultAsync(x => x.Contacts.Any(y => y.Email == email));
优化冗余代码
删除_dataContext.Contacts.Add(newContact);这一行,避免重复跟踪实体引发潜在问题。
内容的提问来源于stack exchange,提问作者Hedimin
相关产品推荐
相关产品推荐

