我有以下课程:
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 时,如何插入新车、有时更新并插入新位置?