2009-05-26 215 views
6

如何使用LINQ to SQL(ASP.Net/C#)中的特定ID更新記錄?Linq更新記錄

+0

請參閱[本文](http://stackoverflow.com/questions/909960/update-using-linq) – 2009-05-26 10:55:30

回答

0

小心張貼一些你刺過的示例代碼。

如果是LINQ2SQL,那麼就應該使用LINQ的DataContext使用Where<T>()條款檢索您的對象,更新對象屬性,然後調用DataContext.SubmitChanges()

15

你可以做這樣一個簡單的問題...

var record = 
(
    from x in db.TableName 
    where x.Id == 12345 
    select x 
) 
.Single(); 

record.DateUpdated = DateTime.Now; 

db.SubmitChanges(); 

希望它能幫助:)

0

看看這段代碼爲例。

void UpdateRow(Int32 intID) 
{ 
    bool IsSuccessfullyUpdated = false; 

    var db = new DataContext(); 
    try 
    { 
     var dbCstInfo = db.TableName 
      .Where(w => w.ID == intID) 
      .SingleOrDefault(); 

     if (dbCstInfo != null) 
     { 
      dbCstInfo.IsActive = !dbCstInfo.IsActive; 
      dbCstInfo.Name = "BJP"; 
      dbCstInfo.Comp = "PVtal"; 
      db.SubmitChanges(); 
      IsSuccessfullyUpdated = true; 
     } 
    } 
    catch 
    { 
     IsSuccessfullyUpdated = false; 
    } 

    return IsSuccessfullyUpdated; 

}