EF 核心实体 Post 将其他实体作为属性的实体出错

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

情况:

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.

第二行出现错误:

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

使用 EF 核心 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 无法识别附加的助手(和回合)作为数据库中已有的实体,而是将它们视为需要创建的新实体。

您可以通过附加 Round 和您从 api 调用中反序列化的 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 方法也会遇到同样的问题,所以要小心。

希望这能解决您的问题。