Posts tagged LINQ to SQL
Easy Data-loading with LINQ-to-SQL and LINQ-to-XML
Mar 20th
.Net 3.5 had some nice tricks in it. LINQ-to-XML was one of them. With the new "X"-types, you can make working with XML really easy.
VB.Net 9 takes it one step further, and lets you write XML in your code without strings.
"Hey Rich, that’s old news," I hear you say. "And who’s interested in VB today anyway?"
Well, apparently there are a lot of VB-er’s still out there. I am mainly a C# developer myself, but I found that VB was perfect for a problem I had recently - loading of XML data into a SQL Server table.
The LinqDataSource and the Hidden Viewstate
Feb 21st
Yesterday I thought I’d learn about the LinqDataSource in ASP.Net 3.5, and got an interesting surprise.
The new LinqDataSource can also be used with a LINQ-to-SQL model to perform updates. You simply add the DataSource to your page, set the table name, and set EnableUpdate to true. Then, using a standard DataControl, you can make updates to your data entities.
The question is, how does this work? It appears to be a bit magical. More >
How to Update Data with LINQ-to-SQL
Feb 18th
When learning LINQ-to-SQL, it’s not immediately obvious how to do an update. Querying is easy, and there are methods for inserting and deleting. Updating usually occurs by modifying an object already known to the DataContext and then calling SubmitChanges on the context.
var product = (from p in dataContext.Products where p.ProductID == 1 select p).Single(); product.Name = "Richard's product"; dataContext.SubmitChanges();
It’s nice to see that MSDN documentation actually addresses the obvious arising question:
Q. Can I update table data without first querying the database?
A. Although LINQ to SQL does not have set-based update commands, you can use either of the following techniques to update without first querying:
- Use ExecuteCommand to send SQL code.
- Create a new instance of the object and initialize all the current values (fields) that affect the update. Then attach the object to the DataContext by using Attach and modify the field you want to change.
How to See the SQL Generated by a LINQ to SQL Command
Feb 14th
Quick tip: If you want to see the SQL generated by LINQ to SQL for a query or command, simply set the Log property of your generated DataContext class to an instance of a TextReader.
If this is your code:
using System; using System.Linq; using System.Data.Linq; namespace LINQtoSQLConsole { class Program { static void Main(string[] args) { var db = new NorthwindDataContext(); // Use the console to see the SQL db.Log = Console.Out; // A query var cust = db.Customers.Single( c => c.CustomerID == "ALFKI"); // An update cust.Region = "Northwest"; db.SubmitChanges(); } } }
… then this is what you’ll see:
Pretty good, eh?

