简体   繁体   中英

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

Situation:

  • Code First C# Azure Function for Posting a new Activity
  • Activity has Id, Helper and Round. Last two are also entities, ie FKs
  • Database is Azure SQL
  • Whilst I can Post new Helpers and Rounds, when posting a new Activity using existing Helper and Round... I'm Getting this error:
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.

Error occurs on 2nd line:

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

Using EF Core 3.1.14
GitHub Project (See API): https://github.com/djaus2/mslearn-staticwebsite-3entities

NB: The following does work (ie Submitting new Helper and Round):

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/

Result returned:

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

Okay so looking at the code the issue you have is that ef does not recognize the helper (and the rounds) attached as entities already in database but instead sees them as new entities that need to be created.

You can solve this by attaching the Round and the Helper you deserialized from the api call.

[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);
}

This tells ef to assume they are from the database and such you do not need to create them. You will have the same issue with the PUT method too so be careful of that.

Hope this fixes your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM