Problem
I am implementing a UnitOfWork and a Repository style data access layer for my web application. I want to audit changes to the database using a custom table I have made. The problem occurs when a new item is added to the context. The item is added to the context, however SaveChanges() method has not been called so the entity is still in the Added state. This means that is has not been assigned a primary key, which means I can not create an audit record and calling SaveChanges() from the repository would violate the repository coding style. Is there a way to get the primary key of an entity in the added state?
Attempted Solution
The only solution that I can think of is to use random GUIDs so that the client can generate them. I am a little hesitant because I have heard that using random GUIDs as the identity field can be costly.
Code
//Method in my repository class
public void Insert(T entity)
{
//Adds the entity the context
dbSet.Add(entity);
Audit audit= new Audit
{
Created = DateTime.Now,
PrimaryKey = entity.Key, //This is not set because the State of the entity is still Added
};
Context.Audits.Add(audit);
}
Simple answer is you can’t do this in a distributed environment. You can’t guarantee that the ID will be the same once the item is persisted.
Using client generated GUIDs does solve the problem. This is the approach I normally take, though let’s not start a debate on that! You will mostly find the outcome is 50/50. Both have pros and cons. For your scenario, it works!