一、更新實體:
EF的DbContext可以實作對一個對象進行更新,而不需要再一次将對象讀入記憶體進行修改,而是采用Attach的方式。
Student stud ;
// Get student from DB
using (var ctx = new SchoolDBEntities())
{
stud = ctx.Students.Where(s => s.StudentName == "New Student1").FirstOrDefault<Student>();
}
// change student name in disconnected mode (out of DBContext scope)
if (stud != null)
{
stud.StudentName = "Updated Student1";
}
//save modified entity using new DBContext
using (var dbCtx = new SchoolDBEntities())
{
//Mark entity as modified: 這裡采用entity的主鍵進行比對。是以,采用這種方法時,必須確定主鍵已經設定。
dbCtx.Entry(stud).State = System.Data.EntityState.Modified;
dbCtx.SaveChanges();
}
二、添加或者是更新實體
對一個實體,如果尚未存在于資料庫,我們的更新将會失敗。是以,大多數情況我們得先去通路資料庫,判斷是否可以更新。而EF有提供一個新的方法。如果一個實體不存在,就添加;否則更新。具體如下:
dbCtx.Students.AddOrUpdate(stud);
另外,我還沒有發現如何對Related的Entity進行更新的方式,特别是Collection,目前我采用的是直接設定相關的Entity的狀态為Modified。請知道的大神指點一下。
相關參考:
http://stackoverflow.com/questions/19322532/updating-a-detached-entity-in-entity-framework-with-related-entites
http://www.entityframeworktutorial.net/EntityFramework4.3/update-many-to-many-entity-using-dbcontext.aspx
http://stackoverflow.com/questions/18274408/entity-framework-update-method-to-object-with-collection
http://codereview.stackexchange.com/questions/37304/update-only-modified-fields-in-entity-framework
添加或者是更新:http://stackoverflow.com/questions/10075495/add-or-update-an-entity-without-knowing-if-its-exists