Error: response status is 400 while trying to fill database

Viewed 37

In my web api I was trying to fill database with some object, here is method:

 try
    {
        var ac = await _dataContext.Accounts.FirstOrDefaultAsync(x => x.Contacts.Any(y => y.Email == email));
        
        var newContact = new Contact();
        newContact.FirstName = firstName;
        newContact.SecondName = secondName;
        newContact.Email = email;
        ac.Result.Contacts.Add(newContact);
    
        _dataContext.Contacts.Add(newContact);
        await _dataContext.SaveChangesAsync();
    
        return Ok();
    }
    catch (Exception e)
    {
        return BadRequest(e);
    }

After executing this with data, I got 400 error responce. Database 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; }
}

Where is the mistake?

Upd: 400 responce problem was with catch block. After fixing that, I get: Object reference not set to an instance of an object at line ac.Result.Contacts.Add(newContact);

1 Answers

missing the await here as youre using FirstOrDefaultAsync not FirstOrDefault

var ac = await _dataContext.Accounts.FirstOrDefaultAsync(x => x.Contacts.Any(y => y.Email == email));
Related