I'm using EF code first for developing my 3 layer WinForm Application, I used disconnected POCO
s as my model entities. All my entities inherited from BaseEntity
class.
I used disconnected POCO
s, so I handle entity's State
on client side, and in ApplyChanges()
method, I attach my entity graph(e.g An Order
with it's OrderLines
and Products
) to my DbContext
and then synch each entity's State
with it's client side State
.
public class BaseEntity
{
int _dataBaseId = -1;
public virtual int DataBaseId // DataBaseId override in each entity to return it's key
{
get { return _dataBaseId; }
}
public States State { get; set; }
public enum States
{
Unchanged,
Added,
Modified,
Deleted
}
}
So, when I want to save a graph of related entities, I used following methods:
public static EntityState ConvertState(BaseEntity.States state)
{
switch (state)
{
case BaseEntity.States.Added:
return EntityState.Added;
case BaseEntity.States.Modified:
return EntityState.Modified;
case BaseEntity.States.Deleted:
return EntityState.Deleted;
default:
return EntityState.Unchanged;
}
}
public void ApplyChanges<TEntity>(TEntity root) where TEntity : BaseEntity
{
_dbContext.Set<TEntity>().Add(root);
foreach (var entry in _dbContext.ChangeTracker
.Entries<BaseEntity>())
{
BaseEntity stateInfo = entry.Entity;
entry.State = ConvertState(stateInfo.State);
}
}
But if my graph contains 2 or more entities with the same key i give this error :
An object with the same key already exists in the ObjectStateManager...
How can i detect entities with the same keys in my graph(root
) and make them unique in my ApplyChanges()
method?