【发布时间】:2015-07-29 10:04:53
【问题描述】:
我有一个使用 web api 2 开发的 web 服务,它使用 ef 6 将数据保存回数据库。
我的数据结构如下;
public class User
{
[Key]
public int UserId { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
}
public class Contact
{
[Key]
public int ContactId { get; set; }
public string ContactName { get; set; }
public int CreatedById { get; set; }
[ForeignKey("CreatedById")]
public User CreatedBy { get; set; }
public int ModifiedById { get; set; }
[ForeignKey("ModifiedById")]
public User ModifiedBy { get; set; }
}
public class Note
{
[Key]
public int NoteId { get; set; }
public string Notes { get; set; }
public int ContactId { get; set; }
[ForeignKey("ContactId")]
public Contact Contact { get; set; }
public int CreatedById { get; set; }
[ForeignKey("CreatedById")]
public User CreatedBy { get; set; }
public int ModifiedById { get; set; }
[ForeignKey("ModifiedById")]
public User ModifiedBy { get; set; }
}
我使用样板代码尝试保存对 web api 中注释的修改,如下所示
// PUT: api/Notes/5
[ResponseType(typeof(void))]
public IHttpActionResult PutNote(int id, Note note)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != note.NoteId)
{
return BadRequest();
}
db.Entry(note).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!AttachmentExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
但是,当修改实体状态的行被执行时,我得到以下异常。
附加“用户”类型的实体失败,因为同一类型的另一个实体已经具有相同的主键值。如果图中的任何实体具有冲突的键值,则在使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时,可能会发生这种情况。这可能是因为某些实体是新实体,尚未收到数据库生成的键值。在这种情况下,使用“添加”方法或“已添加”实体状态来跟踪图形,然后将非新实体的状态设置为“未更改”或“已修改”。
我觉得这很令人费解,因为我没有手动附加任何实体,而且此时 db.ChangeTracker.Entries() 是空的。我原以为 EF 会处理同一实体可以在树中多次引用的事实。
有没有人遇到过这个问题,有没有人有解决方案?
非常感谢,
尼尔。
【问题讨论】:
-
您甚至没有对
note参数执行任何操作。如果您正在发出PUT请求,请至少修改一个属性。 -
修改会在客户端进行并发送到 web api 请求,所以修改已经包含在 note 参数中。
-
我认为 Amit 为您指明了正确的方向。请参阅下面的答案。
标签: c# entity-framework-6 asp.net-web-api2