我有这个控制器动作:
[HttpGet]
[Route("api/person/test/{id}")]
public IHttpActionResult Test(Guid id)
{
var person = this.PersonManager.Get(id);
person.Lastname = "Jameson";
this.PersonManager.Save(person);
return Ok(true);
}
此保存方法的深层称为:
protected void Add<T>(T source, MyEntities context, bool isNew) where T : class
{
if (isNew)
{
context.Set<T>().Add(source);
}
else
{
var entry = context.Entry(source);
if (entry.State == EntityState.Detached)
{
context.Set<T>().Attach(source);
entry.State = EntityState.Modified;
}
}
}
执行此操作时出现此错误:
附加“Model.Person”类型的实体失败,因为另一个实体 相同类型的实体已具有相同的主键值。这个 使用“附加”方法或设置状态时可能会发生 如果图中的任何实体具有,则实体为“未更改”或“已修改” 冲突的关键值。这可能是因为一些实体是新的和 尚未收到数据库生成的键值。在这种情况下使用 “添加”方法或“已添加”实体状态可跟踪图表和 然后将非新实体的状态设置为“未更改”或“已修改”为 合适的。
它出现在context.Set<T>().Attach(source)
行。
PS:这是question的后续/衍生。
答案 0 :(得分:0)
试试这个
if (!context.Set<T>().Local.Contains(source))
{
context.Set<T>().Attach(source);
}
context.Entry(source).State = EntityState.Modified;