title: Problem editing uploaded file in Entity Framework C# ASP.NET
body: <p>Im having problems when i try to edit the Document object.</p>
  
  <p>Im getting exceptions like:</p>
  
  <blockquote>
    <p>A referential integrity constraint violation occurred: The property value(s) of 'Documento.Id' on one end of a relationship do not match the property value(s) of 'File.FileId' on the other end.'</p>
  </blockquote>
  
  <p>Any recommended solution?</p>
  
  <pre><code>[HttpPost]
          [ValidateAntiForgeryToken]
          public ActionResult Edit([Bind(Include = "Id,Nombre,Descripcion,CajaId,AreaId")] Documento documento, HttpPostedFileBase upload)
          {
  
  
              if (ModelState.IsValid)
              {
                  if (upload != null &amp;&amp; upload.ContentLength &gt; 0)
                  {
                      if (documento.File != null)
                      {
  
                          db.Files.Remove(documento.File);
                          db.SaveChanges();
                      }
  
                      var pdf = new File
                      {
                          FileName = System.IO.Path.GetFileName(upload.FileName),
                          FileType = FileType.Pdf,
                          ContentType = upload.ContentType,
                          DocumentoId = documento.Id
                      };
                      using (var reader = new System.IO.BinaryReader(upload.InputStream))
                      {
                          pdf.Content = reader.ReadBytes(upload.ContentLength);
                      }
  
                      documento.File = pdf;
                  }
  
  
                  db.Entry(documento).State = EntityState.Modified;
                  db.SaveChanges();
                  return RedirectToAction("Index");
              }
              ViewBag.AreaId = new SelectList(db.Areas, "Id", "Nombre", documento.AreaId);
              ViewBag.CajaId = new SelectList(db.Cajas, "Id", "CodigoUnico", documento.CajaId);
              return View(documento);
          }
  </code></pre>