我有类似这样的车型:如何在实体的属性引用同一个实体时删除实体?
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
有不同Stops
,然而,许多Stops
可以有相同的Owner
。
予加载使用Include
如下完整Line
实体:
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);
}
使用上面可以装入一个Line
实体,其Stops
实体及其Owners
,其在这种情况下是一样的。
现在,当我试图删除Line
实体我做的:
dbSet.Attach(entity);
dbSet.Remove(entity);
不过,我得到异常:
附加型“所有者”的实体失败,因为另一个实体相同类型已具有相同的主键值。如果图中的任何实体具有冲突的键值,则使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时可能会发生这种情况。这可能是因为一些实体是新的并且还没有收到数据库生成的关键值。在这种情况下,使用'Add'方法或'Added'实体状态来跟踪图形,然后根据情况将非新实体的状态设置为'Unchanged'或'Modified'。
我假设这是因为Stops
都有相同的Owner
。但是,当加载Line
时,Owner
不是相同的实体,而是每个Stop
独立创建的2个实体。
如何在这种情况下删除Line
实体?
检查此[链接](http://stackoverflow.com/questions/30350058/attaching-an-entity-of-type-x-failed-because-another-entity-of-the-same-type)帮助。如果实体从上下文加载,则不要附加它。 – Sarang
@Sarang实体被分离,因为我使用了'AsNoTracking()'。 –