0

我有一个多对多的关系模型:更新实体一对多的关系

public class Transport 
{ 
    ... 
    public virtual ICollection<Remark> CargoRemarks { get; set; } 
    ... 
} 

public class Remark 
{ 
    public virtual ICollection<Transport> Transports { get; set; } 
} 

在某些情况下,我必须更新包含一些言论我的运输模式。添加或删除备注时,不附加模型(由于某些架构决策,这不能完成)。

但是没有我的交通运输已经改变发表任何言论,我的传送对象更新失败:

'...Transport' 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.

例子:

  • 创建我的运输模式,并插入到数据库一些言论。一切工作正常。
  • 在稍后的时间,这个插入的模型会再次加载并分离。
  • 没有改变(没有添加也没有删除模型中的任何注释)我的模型我想更新它。这导致这个错误消息。

这是我打电话是为了更新实体的方法:

public virtual void Update(TEntity entityToUpdate) 
{ 
    dbSet.Attach(entityToUpdate); 
    context.Entry(entityToUpdate).State = EntityState.Modified; 
} 
+0

林现在有同样的问题。 –

回答

0

从我的角度看您的问题不相关的M2M关系。这与Attach相同。

我建议的一件事是考虑重新加载实体从数据库而不是附加。背后的原因是,您无法确定此实体是否以您试图附加的形式存在于数据库中。

如果这不是一个选项,你尝试过没有附加实体?如果它已经拥有了实体按键,应适当根据自我更新:

https://msdn.microsoft.com/en-us/data/jj592676.aspx

+0

即使没有附加实体,问题也会出现。当我不更改(添加/删除)任何注释时,问题不会显示。 – mosquito87