Tool:Visual Studio 2015 Ultimate Update 3 
OS:Windows 10
.NET Framework : 4.6.x
Entity Framework 6.x
Q:如何在Entity Framework 開發方式中,只更新資料表部分欄位?
A:使用更新資料表欄位時,以Northwind資料庫Categories資料表為例,通常我們會這樣寫 :
NorthwindEntities db = new NorthwindEntities( ); 
var c = db.Categories.Find( 1 ); 
c.CategoryName = "Beverages999"; 
c.Description = "Soft drinks, coffees, teas, beers, and ales999"; 
db.SaveChanges( ); 
但這樣會同時更新CategoryName與Description欄位的值。
若為了某些理由,我們只想要更新CategoryName而不想更新Description欄位,這時可以這樣寫,在呼叫SaveChanges之前,將資料庫對應的屬性之IsModified設定為false:
NorthwindEntities db = new NorthwindEntities( ); 
var c = db.Categories.Find( 1 ); 
c.CategoryName = "Beverages999"; 
c.Description = "Soft drinks, coffees, teas, beers, and ales999"; 
db.Entry( c ).Property( x => x.Description ).IsModified = false; 
db.SaveChanges( ); 
這樣更新資料庫欄位時,就只會更新CategoryName 。
 
 
沒有留言:
張貼留言