I am trying to add a new item into the database (with 1=>M relationship) and am stuck at selecting it in the method. How to connect this new contact to the existing account?
Method:
var contacts = _dataContext.Accounts.Select(a => a.Contacts.Where(c=>c.Email==email));
var newContact = new Contact();
newContact.FirstName = firstName;
newContact.SecondName = secondName;
newContact.Email = email;
_dataContext.Contacts.Add(newContact);
await _dataContext.SaveChangesAsync();`
Database structure:
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; }
}
CodePudding user response:
You need to either set AccountId
to the Account.Id
's value and add/update save the new Contact
, or you can simply add the Contact
entity to the Account
's Contacts
list and update save it.
if you're simply trying to fetch a contact that has an email listed in one of their contact infos, for example '[email protected]' then you can do _dataContext.Accounts.FirstOrDefaultAsync(x => x.Contacts.Any(y => y.Email == "[email protected]"))
I'm not sure that this is exactly what you want, but that'll do it, if you want the existing contacts as well as the main Account
object, then you also need to remember to .Include(x => x.Contacts)
, so that it'll be attached to the entity you fetch, and thus you can easily add a new contact to the list and save it, without having to manually attach stuff