2

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.

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

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
inno
  • 376
  • 2
  • 15
  • Does this answer your question? [How can I retrieve Id of inserted entity using Entity framework?](https://stackoverflow.com/questions/5212751/how-can-i-retrieve-id-of-inserted-entity-using-entity-framework) – Guru Stron May 17 '23 at 13:51
  • 1
    You didn't post any Entity Framework code. There's no `InsertItem` or `ReplaceItem` in EF, nor is it needed. When you call `SaveChanges` **all** changes are detected and stored. Any generated IDs are automatically retrieved. BTW all means *all* - if there are any pending delete when your `InsertItem` calls `SaveChanges`, you'll end up with DELETEd items – Panagiotis Kanavos May 17 '23 at 14:00
  • 1
    BTW there's no need for `SaveItemAsync` either - just call `context.Update(item)`. If `item`'s PK has a value, EF will generate an UPDATE. If not, it will generate an INSERT. This very well documented – Panagiotis Kanavos May 17 '23 at 14:03

1 Answers1

1

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.

  • Consider using DbContext.Update or DbSet.Update method which will perform key checking for you (see the Remarks section).

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    You should stress that `SaveChanges` saves all changes, including DELETEs, otherwise the OP's next question may be "Why does my Insert delete 42 records?" – Panagiotis Kanavos May 17 '23 at 14:01
  • 1
    PS: Also that `Update` will Insert or Update based on the values of the entity's PK properties, there's no need to check whether to Add or Update – Panagiotis Kanavos May 17 '23 at 14:04