2012-04-11 49 views
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); 
    } 

它打破了「分貝。 SaveChanges'因爲它說'不能在對象'dbo.Car'中插入重複鍵''。

如果我刪除'db.Location.Add(locacao);',所以它適用於汽車(插入和更新),但沒有位置被添加到數據庫中。

當數據庫中沒有汽車ID時,如何插入新車,何時更新以及插入新位置?

回答

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(); 
+0

完美!非常感謝。 – MuriloKunze 2012-04-11 12:29:58