Guest User

Untitled

a guest
Jul 25th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. Insert/update multiple objects
  2. public class Location
  3. {
  4. public int Id { get; set; }
  5. public string Description { get; set; }
  6. public string CarId { get; set; }
  7. public Car Car { get; set; }
  8. }
  9.  
  10. public class Car
  11. {
  12. public string Id { get; set; }
  13. public string Color { get; set; }
  14. }
  15.  
  16. <div>@Html.LabelFor(location => location.Description)</div>
  17. <div>@Html.EditorFor(location => location.Description)</div>
  18.  
  19. <div>@Html.LabelFor(location => location.Car.Id)</div>
  20. <div>@Html.EditorFor(location => location.Car.Id)</div>
  21.  
  22. <div>@Html.LabelFor(location => location.Car.Color)</div>
  23. <div>@Html.EditorFor(location => location.Car.Color)</div>
  24.  
  25. [HttpPost]
  26. public ActionResult Create(Location location)
  27. {
  28. if (ModelState.IsValid)
  29. {
  30. Car car = db.Car.Find(location.Car.Id);
  31.  
  32. if (car != null)
  33. db.Entry(car).CurrentValues.SetValues(location.Car);
  34. else
  35. db.Car.Add(location.Car);
  36.  
  37. db.Location.Add(locacao);
  38. db.SaveChanges();
  39.  
  40. return RedirectToAction("Index");
  41. }
  42.  
  43. return View(locacao);
  44. }
  45.  
  46. db.Location.Add(locacation);
  47. // You can also use another way to find if you are working with a new Car
  48. // like location.Car.Id == 0
  49. if (db.Car.Any(c => c.Id == location.Car.Id))
  50. {
  51. db.Entry(location.Car).State = EntityState.Modified;
  52. }
  53. db.SaveChanges();
Add Comment
Please, Sign In to add comment