繁体   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