0

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?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • You might have a look at my answer on [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent/39557606#39557606). – Murat Yıldız Sep 18 '16 at 12:32

2 Answers2

0

Try setting state without attaching, like:

dataContext.Entry(entity).State = EntityState.Deleted;

What you are doing, is that you are check if state of entity has not already been set to Deleted then set its state to Deleted. This is fine, but if state of entity has already been set to Deleted, you are trying to attach and remove. It is unnecessary. If entity state is Deleted it measn that it is not Detached, there is no need to re-attach and re-delete it.

Adil Mammadov
  • 8,476
  • 4
  • 31
  • 59
0

If you just want to delete an entity you can use direct SQL statement, like this

dataContext.Database.ExecuteSqlCommand("delete from YOURTABLE where id=@id", new SqlParameter("@id", entity.id));
Sergey L
  • 1,402
  • 1
  • 9
  • 11