2011-02-27 38 views
4

我在谷歌搜索,但它似乎太明顯,沒有人談論這一點。如何使用EF更新控制器中的對象?

我有我的表的存儲庫,我想能夠更新我的分貝。

在LINQ2SQL你有這樣的:

public void SaveCar(Car car) 
{ 
    if (carTable.GetOriginalEntityState(car) == null) 
    { 
     carTable.Attach(product); 
     carTable.Context.Refresh(RefreshMode.KeepCurrentValues, car); 
    } 
    carTable.ContextSubmitChanges(); 
} 

,並在控制器,只需撥打該帖子編輯方法這個方法。

我如何在EF中做這樣的事情?更好的方法。

我看到使用TryUpdateModel(模型)的代碼,但我不知道該更新了我對DB或我得先挑對象和使用的FormCollection更新...

我我很困惑,我只需要從表格中獲取一輛車,並使用數據庫中的相同ID更新汽車。那麼,我必須在控制器和存儲庫中做什麼?

謝謝。

編輯:如果我不清楚,我真的不知道,如果我把那裏是我需要轉換到EF。我只想知道如何使用EF更新對象的實例(EFCodeFirst就是我使用的)。我如何從表單接收實例並在db中更新它。

+0

檢查這個答案:http://stackoverflow.com/questions/3594515/how-to-update-an-entity-in-entity-framework-4-net/3594608#3594608它不是直接關係到MVC,但它顯示了處理儲蓄的兩種不同方法。在MVC中使用TryUpdateModel。 – 2011-02-28 07:05:56

+0

我的上下文沒有ObjectStateManager(我的上下文是由EFCodeFirst手動創建的),所以我不能使用它。但是,謝謝:) – 2011-02-28 13:05:04

回答

2

一個月,沒有答案,是時候autorespond。

回答我的問題是:

在控制器是一樣的東西:

if (ModelState.IsValid) 
    repo.SaveCar(car); 

,並在回購:

context.Entry(Car).State = EntityState.Modified; 

只是,這是保存對象的方法。

2

TryUpdateModel方法可用於使用它的屬性名稱和web請求中指定的值之間的映射爲對象分配值。

[HttpPost] 
public ActionResult Edit(int id, FormCollection form) 
{ 
    Car entity = new Car { Id = id }; 

    // This will attach the car entity to the content in the unchanged state. 
    this.EntityFrameworkObjectContext.Cars.Attach(car); 

    TryUpdateModel(entity, form.ValueProvider.ToXYZ()); // Can't remember the exact method signature right now 

    this.EntityFrameworkObjectContext.SaveChanges(); 
    ... 
} 

當連接到上下文中的實體,你基本上只是通知你有一個實體,這是他應該照顧方面:話雖這麼說,你可以做這樣的事情達到同樣的行爲的。一旦實體被連接,上下文將跟蹤對其進行的更改。

但是此方法僅適用於標量屬性,因爲導航屬性不會使用此方法更新。如果您啓用了外鍵屬性(如分配給某個類別的產品也具有將這兩個鏈接關聯的CategoryId屬性),則應該仍然可以使用此方法(因爲導航屬性使用標量屬性進行映射)。

編輯:另一種方法是接受汽車實例作爲參數:

[HttpPost] 
public ActionResult Edit(int id, Car car) 
{ 
    Car entity = new Car { Id = id }; 

    // This will attach the car entity to the content in the unchanged state. 
    this.EntityFrameworkObjectContext.Cars.Attach(entity); 

    // It is important that the Car instance provided in the car parameter has the 
    // the correct ID set. Since the ApplyCurrentValues will look for any Car in the 
    // context that has the specified primary key of the entity supplied to the ApplyCurrentValues 
    // method and apply it's values to those entity instance with the same ID (this 
    // includes the previously attached entity). 
    this.EntityFrameworkObjectContext.Cars.ApplyCurrentValues(car); 
    this.EntityFrameworkObjectContext.SaveChanges(); 
    ... 
} 

你也可以推出自己的ModelBinder的,實際上有你的實體框架上下文的引用,看起來是否指定了Car.Id在表單/查詢中。如果存在ID,您可以抓取實體以直接從上下文進行更新。此方法需要一些努力,因爲您必須確保先搜索ID,然後應用所有指定的屬性值。如果你有興趣,我可以給你一些檢查。

+0

這很好,但我認爲這是更清潔,如果我在編輯方法而不是FormCollection中接收Car實例。我認爲有一種方法可以直接更新我的實體。 – 2011-02-28 13:07:14

相關問題