1 public bool UpdateEmloyeeInfo(EmployeInfo employeInfo) 2 { 3 bool flg = false; 4 try 5 { 6 using (UserManageDB db = new UserManageDB()) 7 { 8 if (employeInfo.ID > 0) 9 { 10 EmployeInfo employer = db.EmployeInfo.Single(x => x.ID == employeInfo.ID); 11 if (employer == null) 12 throw new ArgumentOutOfRangeException("employeInfo"); 13 db.Entry(employer).CurrentValues.SetValues(employeInfo); //更新實體 14 db.SaveChanges(); 15 flg = true; 16 } 17 else 18 { 19 db.EmployeInfo.Add(employeInfo); //插入實體 20 db.SaveChanges(); 21 flg = true; 22 } 23 } 24 25 return flg; 26 } 27 catch (Exception) 28 { 29 30 throw; 31 } 32 33 }
http://www.cnblogs.com/terrysun/archive/2011/07/21/2112840.html
ADO.NET Entity提共的默認更新數據的方法是:
- 先找出要更新的對象(訪問一次數據庫)
- 賦新值
- 調用 xxxEntities.SaveChange() 方法(需要再次訪問一次數據庫)
一個update操作需要訪問2次數據庫, 多用戶大數據量的環境下這樣的性能確實不怎么樣, 理想化的操作當然是只進行第2,3步.
上面的代碼是一個擴展方法,任何ObjectContext的子類也就是xxxEntities才可以調用UpdateEntity方法
- 第一個參數entity就是要更新的實體對象
- 第二個參數entitySetName就是這個實體對象的 Entity Set Name, 通過entity是不能獲得到的, 只有在調用UpdateEntity方法時傳進來
以pubs數據庫的author表為例, au_id是主鍵, 下面的代碼將會更新author表中au_id為427-17-2319這條數據
PubsEntities pubsEnt = new PubsEntities(); Author auth = new Author() { au_id = "427-17-2319", au_lname = "Dull", au_fname = "Ann", phone = "415 836-7128", address = "3410 Blonde St.", city = "Palo Alto", state = "CA", zip = "99999", contract = true }; pubsEnt.UpdateEntity(auth, pubsEnt.Authors.EntitySet.Name); pubsEnt.SaveChanges();
UpdateEntity方法不足之處是需要傳遞 pubsEnt.Authors.EntitySet.Name這個參數, 有什么好辦法在UpdateEntity內部可以獲得這個屬值?