1

I have models similar to this:

public class Line
{
    public int Id {get; set;}   
    public int FromStopId {get; set;}
    public int ToStopId {get; set;}
    public virtual Stop FromStop {get; set;}    
    public virtual Stop ToStop {get; set;}    
}

public class Stop
{
    public int Id {get; set;}   
    public int OwnerId {get; set;}
    public virtual Owner Owner {get; set;}    
}

Lines have different Stops, however many Stops can have the same Owner.

I load a complete Line entity using Include as follows:

public virtual IQueryable<T> Get(int id, params Expression<Func<T, object>>[] include)
{
    if (include.Any())
    {
        var set = include.Aggregate<Expression<Func<T, object>>, IQueryable<T>>
                            (dbSet, (current, expression) => current.Include(expression));
    }

    return dbSet.AsNoTracking<T>().Where(x => x.Id == id);
}

Using the above I can load a Line entity, its Stops entities and their Owners, which in this case is the same.

Now, when I try to delete the Line entity I do:

dbSet.Attach(entity);
dbSet.Remove(entity);

However, I get the exception:

Attaching an entity of type 'Owner' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

I am assuming that this is caused because both Stops have the same Owner. However, the Owner is not the same entity but 2 entities which are created independently for every Stop when loading the Line.

How can I delete Line entity in such a case?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • Check if this [link](http://stackoverflow.com/questions/30350058/attaching-an-entity-of-type-x-failed-because-another-entity-of-the-same-type) helps. If entity is loaded from context then don't attach it. – Sarang Feb 16 '17 at 09:48
  • @Sarang The entity is detached because I use `AsNoTracking()`. – Ivan-Mark Debono Feb 16 '17 at 09:52

1 Answers1

0

If you just want to delete an entity you can

1)create a new object
2)set its Id property
3)Attach it
4)Delete it

Something like:

var toDelete= new MyEntity{ Id = 123 };
context.MyEntities.Attach(toDelete);
context.MyEntities.Remove(toDelete);
context.SaveChanges();

Deleting a record only requires the Id to be set,this way will probably bypass your problem

George Vovos
  • 7,563
  • 2
  • 22
  • 45