2011-08-09 20 views
2

我需要選擇一組包含IsLocked字段的記錄。然後我需要在事務中立即將IsLocked值從false更新爲true,以便其他程序不會獲取那些已獲取的記錄進行處理,但可以獲取其他未鎖定的記錄。如何使用Linq-To-SQL以事務方式選擇和更新?

下面是我到目前爲止的代碼。它是否正確?我該如何做更新?在foreach中訪問每條記錄,更新值然後SubmitChanges()?看起來,當我運行下面的代碼時,我丟失了與emails相關的集合,因此無法執行我需要執行的處理。提早關閉事務會導致加載的記錄丟失嗎?

要關注這個問題:如何在事務中加載和更新記錄,關閉事務不再鎖定超過必要時間,處理記錄,然後將後續更改保存回數據庫。

using (ForcuraDaemonDataContext ctx = new ForcuraDaemonDataContext(props.EmailLogConnectionString)) 
{ 
    System.Data.Common.DbTransaction trans = null; 
    IQueryable<Email> emails = null; 
    try 
    { 
     // get unlocked & unsent emails, then immediately lock the set for processing 
     ctx.Connection.Open(); 
     trans = ctx.Connection.BeginTransaction(IsolationLevel.ReadCommitted); 
     ctx.Transaction = trans; 

     emails = ctx.Emails.Where(e => !(e.IsLocked || e.IsSent)); 
     /// ??? 
     ctx.SubmitChanges(); 

     trans.Commit(); 
    } 
    catch (Exception ex) 
    { 
     if (trans != null) 
      trans.Rollback(); 

     eventLog.WriteEntry("Error. Could not lock and load emails.", EventLogEntryType.Information); 
    } 
    finally 
    { 
     if (ctx.Connection.State == ConnectionState.Open) 
      ctx.Connection.Close(); 
    } 


    // more stuff on the emails here 

} 

回答