I have a problem when try to create a client, who has a few addresses.
public class Client
{
public int Id { get; set; }
public string Name{ get; set; }
public string Lastname{ get; set; }
public int DNI { get; set; }
public List<Phones> Phones{ get; set; }
}
public class Phone
{
[Key]
public int IdPhone { get; set; }
public int Number{ get; set; }
}
public Client Create(Client client)
{
if (_context.Client.Any(x => x.DNI == cliente.DNI))
throw new AppException("Username " + cliente.DNI + " is already taken");
_context.Cliente.Add(client);
_context.Phones.AddRange(client.Phones);
_context.SaveChanges();
return client;
}
Exception is:
Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
SqlException : Incorrect syntax near 'MERGE'
{
"name": "Franco",
"lastname": "Pachue",
"dni": 55555555,
"phones": [
{
"number": "4444444"
}
]
}
Don't do the AddRange. Just add a ClientId to the Phone entity (assuming that one phone will only belong to one client). The phones will be then saved when adding a Client.
public class Client
{
public int Id { get; set; }
public string Name{ get; set; }
public string Lastname{ get; set; }
public int DNI { get; set; }
public List<Phones> Phones{ get; set; }
}
public class Phone
{
[Key]
public int IdPhone { get; set; }
public int Number{ get; set; }
public int ClientId { get; set; }
public Client Client { get; set; }
}
public Client Create(Client client)
{
if (_context.Client.Any(x => x.DNI == cliente.DNI))
throw new AppException("Username " + cliente.DNI + " is already taken");
_context.Client.Add(client);
_context.SaveChanges();
return client;
}