title: Edit razorview Entity Framework from view model: Error: Store update, insert, or delete statement affected an unexpected number of rows (0)
body: <p>I am using an ASP.NET MVC Razor view and Entity Framework to do CRUD operations. I am using a ViewModel to save changes to the model. I also have file uploads as part of this. The <code>Create</code> function works fine, but the <code>Edit</code> is where I keep getting the error </p>
  
  <blockquote>
    <p>"Store update, insert, or delete statement affected an unexpected number of rows (0)."</p>
  </blockquote>
  
  <p>And I am not sure where the trouble is. </p>
  
  <p>My code is as follows: </p>
  
  <p>View model:</p>
  
  <pre><code>public class ModelNameVM
  {
      public int? PinNumbers { get; set; }
      public HttpPostedFileBase SerialAttachment { get; set; }
      public HttpPostedFileBase CountryAttachment { get; set; }
      public HttpPostedFileBase OtherAttachment { get; set; }
  }
  </code></pre>
  
  <p><strong>Edit.cshtml:</strong></p>
  
  <pre><code>@model ModelName
  ....
  @using (Html.BeginForm())
  {
  
      @Html.HiddenFor(m =&gt; m.Id)
      @Html.TextBoxFor(m =&gt; m.PinNumbers)
      @Html.TextBoxFor(m =&gt; m.SerialAttachment, new { type = "file" })
      @Html.TextBoxFor(m =&gt; m.CountryAttachment , new { type = "file" })
  ...
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code>//GET Edit
  public ActionResult Edit(int? id)
  {
      if (id == null)
      {
          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }
  
      ModelName data= db.entityname.Find(id); //
  
      if (data== null)
      {
          return HttpNotFound();
      }
  
      return View(data);
  }
  
  //POST Edit
  public ActionResult Edit(ModelNameVM model)
  {
      if (!ModelState.IsValid)
      {
          return View(model);
      }
  
      ModelName data = new ModelName
      {
          PinNumbers = model.PinNumbers
      };
  
      if (model.SerialAttachment != null &amp;&amp; model.SerialAttachment.ContentLength &gt; 0)
      {
          string fileName = Path.GetFileName(model.SerialAttachment.FileName);
          ..... 
          model.SerialAttachment.SaveAs(path);
          data.SerialAttachment = path
      }
  
      .... // repeat for CountryAttachment and OtherAttachment 
      db.Entry(data).State = EntityState.Modified;
      db.SaveChanges();
  
      return View("Index", db.entityname.ToList());
  }
  </code></pre>