Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

entity framework: retrieve Id of new entry upon creation

is there a way to get the id of the last entry created without asking for it specifically?

I am doing this:

 public async Task SaveItemAsync(tblUsers item) //change here
        {
            if (item == null) throw new ArgumentException(nameof(item));
            await InitializeAsync();
            if (item.Id == null)
            {
                try
                {
                    await _table.InsertItemAsync(item);
                }
                catch (Exception e)
                {
                    var message = e.Message;
                }
            }
            else await _table.ReplaceItemAsync(item);
        }

anod nothing is returned but an entry with a Id is created on the db.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I alter that so that the Id of the new entry is returned?

>Solution :

If id is database generated Entity Framework should fill it in the inserted entity, i.e.:

_ctx.Items.Add(item);
await _ctx.SaveChangesAsync();
var insertedId = item.Id;

P.S.

Possibly you might want to use something like item.Id == default to check if the id is empty.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading