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?