question

RicardoEnricoJahn-0829 avatar image
0 Votes"
RicardoEnricoJahn-0829 asked RicardoEnricoJahn-0829 commented

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

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.




dotnet-xamarindotnet-aspnet-webapi
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I kind of think this is not an optimal approach. Why didn't you send the parent and child model objects for insert into the database and did everything on the WebAPI side not needing to return an parent ID back to the client-side? And then you make some child objects populating the foreign-key of the child objects with the returned ID and send those objects to the WebAPI for persistence. All of it could have been done on the WebAPI side, if all the objects were sent at one time.

0 Votes 0 ·

I agree. This would be possible too. Maybe easier to handle and less code.
Thanks for the hint.

0 Votes 0 ·

1 Answer

RicardoEnricoJahn-0829 avatar image
0 Votes"
RicardoEnricoJahn-0829 answered

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;


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.