Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Id of newly added Entity before SaveChanges()

I am adding an entity to my database like so:

public TEntity Add(TEntity entity)
{
     return (TEntity)_database.Set<TEntity>().Add(entity);
}

However, the DbSet.Add method isn't returning the newly added entity with the Id etc, it is simply returning the object I passed in to my Add method.

Should it be passing me back the complete new entity including Id, or is it not possible to get the Id before SaveChanges() is called?

like image 573
jcvandan Avatar asked May 17 '11 10:05

jcvandan


People also ask

How do I get an ID after inserting EF core?

EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();

What does the DbContext SaveChanges () method return?

Returns. The number of state entries written to the underlying database. This can include state entries for entities and/or relationships.

When would you use SaveChanges false AcceptAllChanges ()?

Sometimes though the SaveChanges(false) + AcceptAllChanges() pairing is useful. The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts. If context1. SaveChanges() succeeds but context2.


1 Answers

All the call to Add() is doing is effectively registering it with the data context so that the entity can be tracked. No actual operation is done against the database at this time until (as you rightly mention) you call SaveChanges().

I'm assuming that you're using automatically-generated Ids in your table; in this case, it's the database engine which will generate that Id when the record is inserted, and Entity Framework will read this back and populate your entity for you.

So, to confirm your suspicions, no - it's not possible to get the Id before SaveChanges() is called in this case.

Hope this helps!

like image 91
Steve Hobbs Avatar answered Oct 23 '22 23:10

Steve Hobbs