Why I Love LINQ-to-SQL
Oct. 3rd, 2008 09:53 amThe task: given a Scale which may contain one or many ScaleTexts and are thus reflected in the SQL database as a Scales and ScaleTexts table with ScaleTexts having a ScaleId foreign key reference, create the Scale in the database.
The old method: Generate and execute SQL to create a scale in the database and save its id. Methodically go through each of the ScaleTexts and generate and execute SQL to create a ScaleText in the database.
The LINQ method (given items as an IEnumerable(of string) that contains the scale texts for the new scale, and Db represents the DataContext derived object for the project):
To me, this is so much better. I'm not having to move my head from writing VB.NET code to writing Transact-SQL, I can stay within the object model I've been working with all along and just expect the DataContext object to handle actually updating the database. All of my code is compile-time checked, rather having to wait until run-time to find out if I messed up a SQL statement.
Yum.
The old method: Generate and execute SQL to create a scale in the database and save its id. Methodically go through each of the ScaleTexts and generate and execute SQL to create a ScaleText in the database.
The LINQ method (given items as an IEnumerable(of string) that contains the scale texts for the new scale, and Db represents the DataContext derived object for the project):
Dim scale = New Scale() With {.Name = String.Format("{0} - {1}", items.First(), items.Last())} Dim englishId = GetEnglishLanguageId() For i As Integer = 0 To items.Count() - 1 scale.ScaleTexts.Add(New ScaleText() With {.ScaleLabel = items.ElementAt(i), _ .ScaleOrder = i + 1, _ .ScaleValue = i + 1, _ .LangID = englishId}) Next Db.ScaleTexts.InsertAllOnSubmit(scale.ScaleTexts) Db.Scales.InsertOnSubmit(scale) Db.SubmitChanges() Return scale
To me, this is so much better. I'm not having to move my head from writing VB.NET code to writing Transact-SQL, I can stay within the object model I've been working with all along and just expect the DataContext object to handle actually updating the database. All of my code is compile-time checked, rather having to wait until run-time to find out if I messed up a SQL statement.
Yum.