私は次のクラスを持っています:
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; }
}
そしてビュー:
<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>
私がこれを試すとき:
[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);
}
'db.SaveChanges'で壊れ、'オブジェクト'dbo.Car'に重複キーを挿入できません'と表示されます。
'db.Location.Add(locacao);'を削除すると、車(挿入および更新)では問題なく機能しますが、データベースに場所が追加されません。
データベースに車のIDがない場合に新しい車を挿入し、ある場合に更新して、新しい場所を挿入するにはどうすればよいですか?