I am trying to delete a list of detached entities. The entities to be deleted have relationships to other entities (foreign keys), for example:
public class Foo
{
public int BarId {get;set;}
public virtual Bar Bar {get;set;}
}
In some cases, 2 Foo entities might have the same Bar id. However, because these are detached entities and not being tracked by the context, the 2 Foo entities have 2 unique Bar entities.
To delete Foo I'm doing (in a generic repository class):
public virtual void Delete(T entity)
{
DbEntityEntry dbEntityEntry = dataContext.GetEntry(entity);
if (dbEntityEntry.State != EntityState.Deleted)
{
dbEntityEntry.State = EntityState.Deleted;
}
else
{
dbSet.Attach(entity);
dbSet.Remove(entity);
}
}
This works for the first Foo entity only. For other Foo entities where Bar is the same, I get the exception:
Attaching an entity of type failed because another entity of the same type already has the same primary key value
As a work around, I'm setting Foo.Bar = null
before calling Delete()
. This works fine.
However, is there a better way to delete multiple entities from the context?