I use a Repository in the Data layer contains the following method suggested by chrisb for updating entities, the code access the primary key first before update:
var entry = _dbContext.Entry<T>(entity);
// Retreive the Id through reflection
var pkey = _dbset.Create().GetType().GetProperty("Id").GetValue(entity);
if (entry.State == EntityState.Detached)
{
var set = _dbContext.Set<T>();
T attachedEntity = set.Find(pkey); // You need to have access to key
if (attachedEntity != null)
{
var attachedEntry = _dbContext.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(entity);
}
else
{
entry.State = EntityState.Modified; // This should attach entity
}
}
The question is how to use this method with composite primary key: i.e. when the primary key consists of two or more columns.
Update: my problem is with Find() method, for example when I pass two variables to it as a composite PK the attachedEntity is null and I get the exception: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."
update2: here the complete method code after modification
public virtual void Update(T entity, params Object[] pkey)
{
var entry = _dbContext.Entry<T>(entity);
if (entry.State == EntityState.Detached)
{
var set = _dbContext.Set<T>();
T attachedEntity = set.Find(pkey); // You need to have access to key
if (attachedEntity != null)
{
var attachedEntry = _dbContext.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(entity);
}
else
{
entry.State = EntityState.Modified; // This should attach entity
}
}
}
Thanks.