【问题标题】:Web API 2 and EF attach issueWeb API 2 和 EF 附加问题
【发布时间】: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


【解决方案1】:

我认为部分问题在于您的笔记 model 可能永远不会正确加载到 EF 的对象图中进行跟踪。

尝试以下伪(ish)代码:

// 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();

    //Not sure how you're setup, but have EF fetch the note you want
    //to modify from the DB. It is now aware of it and tracking changes.
    var model = _getNoteModelFromDbById(note.NoteId);

    //Now that you have the model from the DB you can map the properties 
    //of the incoming note to your model. Bellow is just a basic example.         
    //I recommend you look into a library called Automapper later on. 

     model.Title = note.Title;
     model.Description = note.Description;
     model.Status = note.Status;

    db.Entry(model).State = EntityState.Modified;

    try
    {
        db.SaveChanges();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!AttachmentExists(id))
            return NotFound();
        else
            throw;
    }
    return StatusCode(HttpStatusCode.NoContent);
}

【讨论】:

  • 感谢您的回复,我可以看到您所说的将如何工作,但是,如果我逐字应用您的示例,这意味着我的控制器必须为对象上的每个属性都有一个声明更新它,这在维护和修改方面并不是特别友好。如果类在以后更新,很可能控制器可能会被遗忘。您已经在建议 automapper 时解决了这个问题,但我发现当使用 automapper 复制属性时,所有相关对象都附加有已添加状态,这显然是不正确的。
  • 您说的代码混乱是正确的。这只是一个例子。您可以通过将属性映射提取到它自己的类来重构它。然后对控制器中的转换器/映射器进行单行调用。理想情况下,这应该通过依赖注入来完成。但是,如果您不熟悉原理,请不要担心。如果这个问题超出了范围。
  • 我现在正在使用手机,但我很乐意稍后发布一些代码示例。
  • 如果可以的话,那就太好了,非常感谢您的帮助。
  • @PercivalMcGullicuddy 能否请您发送代码示例?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 2019-05-15
  • 2019-04-30
相关资源
最近更新 更多