1

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

3
  • 1
    Seems like you are assigning a value to the identity field of helpers table in code. Can you show the creation of that entity May 4, 2021 at 4:11
  • Please show your related code. Usually, you don't want to set the id/primary key yourself.
    – JHBonarius
    May 4, 2021 at 5:53
  • GitHub link is above May 4, 2021 at 12:27

1 Answer 1

1

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.

2
  • Should use using blocks or statements in production code. Also, this is probably not the issue. Read the error message.
    – JHBonarius
    May 4, 2021 at 5:55
  • Thanks,Ihusaan, that works like a charm. I thought it might have something to do with the 'sub-entities' being context. I tried to do that by getting all entity lists in the function to no avail.. May 4, 2021 at 6:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.