首页 > 解决方案 > 具有其他实体作为属性的实体的 EF Core 实体发布错误

问题描述

情况:

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

标签: c#entity-framework-coreazure-functions

解决方案


好的,所以查看代码,您遇到的问题是 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 方法也会有同样的问题,所以要小心。

希望这可以解决您的问题。


推荐阅读