I am developing a program following the Repository pattern which involves a database access with Entity Framework and I have come across a problem. When I try to manipulate the same variable twice in the same context, I am greeted with this exception:
System.InvalidOperationException: Attaching an entity of type
'Syn.Commons.Data.Tests.EntityFramework.Helper.DbModel.DBBox' failed because
another entity of the same type already has the same primary key value.
This can happen when using the 'Attach' method or [...]
I know it comes from the fact that the entity is being used more than once in the same context. However, when I try to use the Detach()
method, it loses all of its navigation properties (i.e., all of them become edit: are reset to the last known values), as stated here (section Detaching Objects):null
In an independent association, the relationship information is not maintained for a detached object.
If I were making queries, I would use AsNoTracking()
, but it is not possible since I am not using them. Here is the Update()
method:
public bool Update(T entity)
{
// Some code to get dbEnt
_context.Set<TDbType>().Attach(dbEnt);
// The following gives an error when manipulating the entity for the second time
//_context.Entry<TDbType>(dbEnt).State = EntityState.Modified;
_context.SaveChanges();
// The following makes the entity "lose" all of its navigation properties
//DetachEntry(_context.Entry(dbEnt));
return true;
}
It seems that both solutions conflict with each other. Is there any way not to track an entity (without explicit queries) while conserving its navigation properties?
Edit: people in the comments were right. Although it did no harm, I did not need
Attach()
. Therefore, the method now looks like this:
public bool Update(T entity)
{
// Some code to get dbEnt
_context.Entry<TDbType>(dbEnt).State = EntityState.Modified;
_context.SaveChanges();
return true;
}