Wednesday, April 11, 2012

Insert/update multiple objects

I have the following class:



public class Location
{
public int Id { get; set; }
public string Description { get; set; }
public string CarId { get; set; }
public Car Car { get; set; }
}

public class Car
{
public string Id { get; set; }
public string Color { get; set; }
}


And a view:



    <div>@Html.LabelFor(location => location.Description)</div>
<div>@Html.EditorFor(location => location.Description)</div>

<div>@Html.LabelFor(location => location.Car.Id)</div>
<div>@Html.EditorFor(location => location.Car.Id)</div>

<div>@Html.LabelFor(location => location.Car.Color)</div>
<div>@Html.EditorFor(location => location.Car.Color)</div>


When i try this:



    [HttpPost]
public ActionResult Create(Location location)
{
if (ModelState.IsValid)
{
Car car = db.Car.Find(location.Car.Id);

if (car != null)
db.Entry(car).CurrentValues.SetValues(location.Car);
else
db.Car.Add(location.Car);

db.Location.Add(locacao);
db.SaveChanges();

return RedirectToAction("Index");
}

return View(locacao);
}


it breaks in 'db.SaveChanges' cause it says 'Cannot insert duplicate key in object 'dbo.Car'.'



If I remove 'db.Location.Add(locacao);', so it works pretty fine for the car(insert and update), but no location is added in database.



How can I do to insert a new car when there is not car's id in database, update when there is, and insert a new location?





No comments:

Post a Comment