2014-04-04 142 views
0

Im新手到Asp.NetMVC3.I試圖用EF4更新我的記錄。我的代碼用於更新記錄。EF4更新記錄?

[HttpPost] 
    public ActionResult Edit(Movie movies) 
    { 
     using(var db = new AmsecDevTestEntities1()) 
     { 
      db.Movies.Attach(db.Movies.Single(m => m.Id == movies.Id)); 
      db.Movies. (movies); //Im stuck here how can i update the record 

     } 
    } 

我試圖用db.Movies.ApplyCurrentValues(電影);。但即時通訊得到一個錯誤,說這裏的上下文不存在。

任何幫助將不勝感激。

回答

0

編輯的行這樣的:

var movie = db.Movies.Single(m => m.Id == movies.Id); 
movie.Name = "Pulp Fiction"; 
db.SaveChanges(); 

OR

context.Entry(movies).State = EntityState.Modified; 
db.SaveChanges(); 

請參閱MSDN文章在這裏:http://msdn.microsoft.com/en-nz/data/jj592676.aspx,看看這節:

附加現有的,但修改實體背景

請注意,如果您附上您,確實需要確保這種情況發生在新的環境中。如果具有相同ID的實體已被上下文跟蹤,則會出現錯誤。

+0

我有很多字段需要更新。我可以如何做到這一點呢? – SparAby

0
Try like this 

Change the state of the entity to Modified: 

db.Movies1.Attach(movie); 
db.ObjectStateManager.ChangeObjectState(movie, EntityState.Modified); 
db.SaveChanges(); 

This marks all properties of movie as modified and will send an UPDATE statement to the database which includes all column values, no matter if the values really changed or not.