2009-11-19 30 views

回答

0

在Linq中批量更新是不可能的,所以你必須選擇你想要更新的學生,遍歷他們,更新字段,然後提交你的數據上下文的變化。

(已經有一些嘗試獲取批量更新工作,例如this,但它沒有正式Microsoft支持。)

1

如果您正在使用LINQ to SQL,那麼你的類的Linq類應該有一個學生採集。

你應該能夠使用簡單的foreach循環來更新它們。完成更新後,只需在Data Context上調用SubmitChanges()。

2
DataContext dc = new DataContext(); 

foreach(var student in dc.Students.Where(SomeCondition)) 
{ 
    student.SomeField = SomeValue; 
    student.SomeOtherField = SomeOtherValue; 
} 
dc.SubmitChanges(); 
0

正如他們所說批量更新不(容易)可能的,所以遍歷每個學生,並在同一時間更新一個可能是最好的解決方案。

This article確實想出了批量更新的方法,但它看起來比它的價值更麻煩。

0

假設你的等級和學生的表都有一個時間戳字段,修改,你可以試試這個:

Public Class ClassesConduit 

    Public Function SaveClasses(ByVal theseClasses As IEnumerable(Of [Class])) As Boolean 
     SaveClasses = False 

     Dim newClasses = theseClasses.Where(Function(c) c.Modified Is Nothing) 
     Dim updatedClasses = theseClasses.Where(Function(c) c.Modified IsNot Nothing) 

     Using db As New ClassesDataContext 
      db.DeferredLoadingEnabled = False 
      db.Classes.InsertAllOnSubmit(newClasses) 
      db.Classes.AttachAll(updatedClasses, True) 

      SaveStudents(theseClasses.SelectMany(Function(c) c.Students), db) 

      SaveClasses = (db.GetChangeSet.Inserts.Count + db.GetChangeSet.Updates.Count) > 0 
      Try 
       db.SubmitChanges() 
      Catch ex As Exception 
       Throw 
      End Try 
     End Using 

    End Function 

    Private Sub SaveStudents(ByVal theseStudents As IEnumerable(Of Student), ByRef db As ClassesDCDataContext) 
     Dim newStudents = theseStudents.Where(Function(s) s.Modified Is Nothing) 
     Dim updatedStudents = theseStudents.Where(Function(s) s.Modified IsNot Nothing) 

     db.Students.InsertAllOnSubmit(newStudents) 
     db.Students.AttachAll(updatedStudents, True) 

    End Sub 
End Class