I was trying to fill data base with wep api and while executing method this problem figurated.
Method:
[HttpPost]
[Route("AddNewContactToExistingAccount")]
public async Task<ActionResult<string>> AddNewContactToExistingAccount(string firstName, string secondName, string email)
{
//Finding contact with same email and adding new contact to account
var ac = await _dataContext.Accounts.FirstOrDefaultAsync(x => x.Contacts.Any(y => y.Email == email));
if (ac==null)
{
return BadRequest("No account with such email in the system. Create new account with new contact");
}
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("");
}
The problem is in ac.Contacts.Add(newContact)
, but I dont know what is wrong here.
Data base strucutre:
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; }
}
Exception: "System.NullReferenceException: Object reference not set to an instance of an object.
"
CodePudding user response:
This exception is because you're trying to access a method/property in a null object. Probably you dont instantiate the Contacts list into your Account class.
CodePudding user response:
FIrst question- Do we have foreign key relationships like 1 account can have multiple contacts Second - While saving the contact you are passing only firstname, secondname, email but accountid is missing which is not nullable. that could be the cause of error.