Easy Data-loading with LINQ-to-SQL and LINQ-to-XML
.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.
SQL Server 2005 and XML Fields
I recently came across the need to load a database with XML data fields in SQL Server 2005. I had a series of XML documents which all needed to be pumped into a table containing a field of type XML. I could have opened up SQL Server Management Studio and fired in a load of strings, but I was a bit concerned that the XML might not be formatted quite correctly, which would have caused problems in the loading process.
Another problem was that I wanted to be able to add dynamic XML. I wanted to generate some XML data on the fly. That’s not so easy with insert statements in SQL.
LINQ-to-SQL and XML Fields
Using my recently-acquired LINQ-to-SQL knowledge, I knew that the Entities generated for an XML field are translated to XElements – the new XML type in .Net 3.5. I also knew that VB 9 lets you create an XElement by using XML in code itself:
So I came up with a plan…
Inserts with LINQ-to-SQL
For data-loading, LINQ-to-SQL is magic. A simple Insert is a piece of cake.
First, create your DataContext using the Visual Studio template, then drag the table you are inserting to onto the DataContext canvas. That gives you an Entity class. You then can create an Entity in your code, call InsertOnSubmit on the DataContext table, then call SubmitChanges on the DataContext itself.
Using Object Property Initializers, you can make this really easy.
Here’s what it looks like with VB.Net using an XML datatype:
(Sorry to have torn the edge off the code there, but it wouldn’t fit nicely in my post at full width. XML can be a little long sometimes.)
The great thing here is that any malformed XML is highlighted (or even automatically corrected) for me by the VB compiler. I can also add parameters and generate lots of different XML using the familiar ASP syntax:
And as SubmitChanges uses a single transaction, the data-loading can easily be an all-or-nothing affair. In addition, any foreign key relationships can easily be taken care of by assigning objects to each other using standard object notation. The DataContext takes care of doing things in the correct order for you.
It’s all super-easy, and takes about 1 minute to get started.