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?
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();
Returns. The number of state entries written to the underlying database. This can include state entries for entities and/or relationships.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With