附近的语法不正确

附近的语法不正确

尝试创建一个有几个地址的客户端时遇到问题。

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;
}


例外是:


  Microsoft.EntityFrameworkCore.DbUpdateException:'更新条目时发生错误。有关详细信息,请参见内部异常。
  
  SqlException:“ MERGE”附近的语法不正确


{
"name": "Franco",
"lastname": "Pachue",
"dni": 55555555,
"phones": [
    {
        "number": "4444444"
    }
]

}

最佳答案

不要执行AddRange。
只需将ClientId添加到Phone实体(假设一个电话仅属于一个客户端)。添加客户端后,电话将被保存。

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;
}

关于c# - “MERGE” Entity Framework 核心附近的语法不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48523410/

10-12 00:26