-->

Id of newly added Entity before SaveChanges()

2020-08-12 18:04发布

问题:

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?

回答1:

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!