2014-04-04 102 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.