I solve the problem with updating the object before saving to the database and getting strange behavior.
I am using Entity Framework 4.1 Code-First in an ASP.NET MVC 3 web application. Here is a model:
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; } }
Each car has a RentPrice. This price must be copied for RentPrice when creating it. The car is selected by the user, so initially Order.RentPrice is 0.
Here I want to copy the price value:
[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); }
It does not work due to an error on SaveChanges that the object has validation errors. OK. I found that you first need to call UpdateModel(order); and then change the values.
So what I have. Work code:
_context.Orders.Add(order); UpdateModel(order); order.RentPrice = 777; _context.SaveChanges();
Not working code:
_context.Orders.Add(order); UpdateModel(order); order.RentPrice = _context.Cars.Find(order.CarId).RentPrice; _context.SaveChanges();
Work code (!):
_context.Orders.Add(order); UpdateModel(order); var t = (double)_context.Cars.Find(order.CarId).RentPrice; order.RentPrice = (decimal)t; _context.SaveChanges();
Can someone please explain what is going on here? Especially the magic on the 3rd and 4th lines in the last block of code.
Update
I get a DbEntityValidationException : "Failed to validate for one or more objects. See more details" EntityValidationErrors property. "From an internal exception:" OriginalValues cannot be used for objects in the added state. "
source share