簡體   English   中英

具有其他實體作為屬性的實體的 EF Core 實體發布錯誤

[英]EF Core Entity Post Error with entity that has other entities as properties

情況:

  • 代碼優先 C# Azure Function 用於發布新活動
  • Activity 有 Id、Helper 和 Round。 最后兩個也是實體,即 FK
  • 數據庫為 Azure SQL
  • 雖然我可以發布新的助手和回合,但在使用現有的助手和回合發布新活動時...我收到此錯誤:
Executed 'ActivitysPost' (Failed, Id=a2e8a556-7b1b-4d0d-995c-65b9c494c802, Duration=26938ms)
[2021-05-03T05:04:29.141Z] System.Private.CoreLib: Exception while executing function: ActivitysPost. 
Microsoft.EntityFrameworkCore.Relational: An error occurred while updating the entries. 
See the inner exception for details. 
Core .Net SqlClient Data Provider: 
Cannot insert explicit value for identity column in table 'Helpers' 
... when IDENTITY_INSERT is set to OFF.

錯誤發生在第 2 行:

            _context.Add(activity);
            await _context.SaveChangesAsync();

使用 EF Core 3.1.14
GitHub 項目(參見 API): https://github.com/djaus2/mslearn-staticwebsite-3entities

注意:以下確實有效(即提交新的助手和回合):

curl --header "Content-Type: application/json" --request POST --data "{'Name':'Recording','Quantity':1,'Round':{'No':1,'Description':'AVSL'},'Helper':{'Name':'FreedyFeelgood','Description':'BlaBlah'}}" http://localhost:7071/api/activitys/

返回結果:

{"id":6,"name":"Recording","quantity":1,"helper":{"id":13,"name":"FreedyFeelgood","description":"BlaBlah"},"round":{"id":7,"no":1,"description":"AVSL"}}

好的,所以查看代碼,您遇到的問題是 ef 無法識別作為已在數據庫中的實體附加的助手(和回合),而是將它們視為需要創建的新實體。

您可以通過附加從 api 調用反序列化的 Round 和 Helper 來解決此問題。

[FunctionName("ActivitysPost")]
public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "activitys")] HttpRequest req,
    ILogger log)
{
    var body = await new StreamReader(req.Body).ReadToEndAsync();
    var activity = JsonConvert.DeserializeObject<Activity>(body);

    ....
    _context.Attach(activity.Helper); // <-- new
    _context.Attach(activity.Round);  // <-- new

    await _context.SaveChangesAsync();
    return new OkObjectResult(activity);
}

這告訴 ef 假設它們來自數據庫,因此您不需要創建它們。 PUT 方法也會有同樣的問題,所以要小心。

希望這可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM