WebAPI Get autogenerated ID of a just created (posted) record

Ricardo Enrico Jahn 116 Reputation points
2021-04-09T12:13:21.32+00:00

Good afternoon,
I have a web API running just fine and a Xamarin forms app on top of it.
There I want to create 1:N relation which is fine in the model but I have the following problem:
(I don't want to post all the code here so I bring it down to the problem).
Model Header
public long header_Id {get;set;}
...several other fields

Model Details
public long details_Id {get;set;}
public long header_Id {get;set;}
....several other fields

The fields header_Id and details_Id are auto-generated as identity-fields in Azure SQL Server

PROBLEM:
I post the header model with "response = await client.PostAsync(uri, content);"
Record is created fine.
BUT now I need the header_Id to create my 1:N Details records.
How can I get the Id of the just created record?

I cannot use any SQL-Command here because as I have an WEBAPI between the App and the SQL-Server I cannot execute SQL queries directly against the database.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,293 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
294 questions
{count} votes

Accepted answer
  1. Ricardo Enrico Jahn 116 Reputation points
    2021-04-09T12:39:13.723+00:00

    Solved it myself :)

    After PostAsync() I have to read based on the response from the post. Then I can deserialize to my model and return this to the original function.

    Here is my code in case somebody needs it:

    response = await client.PostAsync(uri, content);
    var feedback = await response.Content.ReadAsStringAsync();
    YOURMODEL results =    JsonConvert.DeserializeObject<YOURMODEL>(feedback);
    return results;
    
    0 comments No comments

0 additional answers

Sort by: Most helpful