0

私は次のクラスを持っています:

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がない場合に新しい車を挿入し、ある場合に更新して、新しい場所を挿入するにはどうすればよいですか?

4

1 に答える 1

1

Addメソッドは常にオブジェクト グラフにすべてのエンティティを追加するため、db.Car.Add(location.Car)db.Location.Add(location)は場所と車の両方を挿入します。

これを試して:

db.Location.Add(locacation);
// You can also use another way to find if you are working with a new Car 
// like location.Car.Id == 0
if (db.Car.Any(c => c.Id == location.Car.Id)) 
{
    db.Entry(location.Car).State = EntityState.Modified;
}
db.SaveChanges();  
于 2012-04-11T12:19:47.120 に答える