title: Strange entity updating in Entity Framework Code-First
body: <p>I'm solving the problem with updating entity before saving to database and got strange behavior.</p>
  
  <p>I'm using Entity Framework 4.1 Code-First in ASP.NET MVC 3 web application. Here is model:</p>
  
  <pre><code>public class Order
  {
      public int OrderId { get; set; }
      public int CarId { get; set; }
      public DateTime BeginRentDate { get; set; }
      public DateTime EndRentDate { get; set; }
      public decimal RentPrice { get; set; }
      public virtual Car Car { get; set; }
  }
  
  public class Car
  {
      public int CarId { get; set; }
      public string Brand { get; set; }
      public string Model { get; set; }
      public string NumberPlate { get; set; }
      public decimal RentPrice { get; set; }
  }
  </code></pre>
  
  <p>Each Car has a RentPrice. This price should be copied to Order's RentPrice when creating one. The car is selecting by user so initially Order.RentPrice is 0.</p>
  
  <p>Here I want to copy price value:</p>
  
  <pre><code>[HttpPost]
  public ActionResult Create(Order order)
  {
      order.RentPrice = _context.Cars.Find(order.CarId).RentPrice;
  
      if (ModelState.IsValid)
      {
          _context.Orders.Add(order);
          _context.SaveChanges();
          return RedirectToAction("Index");
      }
  
      return View(order);
  }
  </code></pre>
  
  <p>It's not working because of an error on the <code>SaveChanges</code> that entity has validation errors. OK. I found that need first to call <code>UpdateModel(order);</code> and then change values.</p>
  
  <p>So what I have. Working code:</p>
  
  <pre><code>_context.Orders.Add(order);
  UpdateModel(order);
  order.RentPrice = 777;
  _context.SaveChanges();
  </code></pre>
  
  <p><strong>Not</strong> working code:</p>
  
  <pre><code>_context.Orders.Add(order);
  UpdateModel(order);
  order.RentPrice = _context.Cars.Find(order.CarId).RentPrice;
  _context.SaveChanges();
  </code></pre>
  
  <p>Working code (!):</p>
  
  <pre><code>_context.Orders.Add(order);
  UpdateModel(order);
  var t = (double)_context.Cars.Find(order.CarId).RentPrice;
  order.RentPrice = (decimal)t;
  _context.SaveChanges();
  </code></pre>
  
  <p>Can someone explain, please, what is going on here? Especially <em>magic</em> on the 3nd and 4th lines in the last block of code.</p>
  
  <p><strong>Update</strong></p>
  
  <p>I'm getting <code>DbEntityValidationException</code>: "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."
  From the inner exception: "OriginalValues cannot be used for entities in the Added state."</p>