As far as you are using the latest version for EF(4.0,4.1), there is no problem getting the last inserted entity object identity value.
Note The identity column value will be returned only after the inserted statement committed successfully.
1. Insert the Entity Object.
2. Save the Entity Object using database context object SaveChanges() method
3. Don't dispose the database context object.
4. Return the Entity Object from your method.
public Customer AddRecord<Customer>(Customer entity)
{
try {
bool success = entityRepository.AddRecord<Customer>(entity);
if(success)
return entity;
} catch (OptimisticConcurrencyException concurrencyException) {
entityRepository.Dispose();
throw concurrencyException;
} catch (Exception addRecordException) {
entityRepository.Dispose();
throw addRecordException;
}
return null;
}
The
AddRecord
method from the repository looks something like this.
Note. It just code fragment, there are lots of methods that should be contained in the repository.
public bool AddRecord<E>(E entity)
{
this.objectContext.AddObject(GetBaseType(typeof(E)).Name.ToString(), entity);
this.objectContext.SaveChanges();
return true;
}