Reputation: 147
I have two tables in my DB
Class
Student
One Class has many Students
What's the best,more elegant way to update the students of one class, using Linq?
Upvotes: 0
Views: 134
Reputation: 881
Assuming your Class and Student tables both have a timestamp field, Modified, you could try this:
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
Upvotes: 0
Reputation: 6870
As they said batch updates aren't (easily) possible, so iterating over each student and updating one at a time is probably the best solution.
This article does come up with a way to do batch updates, but it looks to be more trouble than it's worth.
Upvotes: 0
Reputation: 180787
DataContext dc = new DataContext();
foreach(var student in dc.Students.Where(SomeCondition))
{
student.SomeField = SomeValue;
student.SomeOtherField = SomeOtherValue;
}
dc.SubmitChanges();
Upvotes: 2
Reputation: 245389
If you are using LINQ to SQL, then your Class Linq class should have a Students collection.
You should be able to update them all using a simple foreach loop. Once your updates are completed, just call SubmitChanges() on your Data Context.
Upvotes: 1
Reputation: 837926
Batch update isn't possible in Linq, so you have to select the students you want to update, iterate over them, update the fields, then submit changes on your data context.
(There have been some attempts to get batch updates working, for example this, but it's not officially supported by Microsoft.)
Upvotes: 0