![](/img/trans.png)
[英]Incorrect syntax near '('. Connection to database with entity framework
[英]Incorrect syntax near 'MERGE' Entity Framework Core
嘗試創建一個有幾個地址的客戶端時遇到問題。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.