Delta Engine Blog

AI, Robotics, multiplatform game development and Strict programming language

Working with DLinq, Linq and Xml

I got my MVP Award Package today ;-) Thats some pretty cool stuff (see on the right side). Now I can not only brag on the internet, but also when running around (crying "I'm a MVP" like a madman).
I also just checked the activity on this blog and I almost get twice as much hits than last month, wtf is going on? Ok, enough of that self-praising. Let's get to some serious stuff.

Lately I've been working a lot on databases, websites and xml data for several projects. I tried out Linq (C# 3.0), still beta last month (see this post about the Linq CTP May 2006) and still find it very useful. This post is about some of the experiences with Linq and especially DLinq, which is for accessing databases very easily. I got a lot of questions from people asking me if Linq is really that useful and instead of answering them one by one, I can now refer to this page and the links here. For this reason this post may become a "little" longer than usual ^^

Lets start with a graphic to let the C++ fanatics (and maybe some Linux freaks too) get more mad at me:
Linq is amazing



Content


Introduction to Linq

If you don't know much about Linq and its uses, check out the official LINQ Project site first.
Linq does basically just simplify queries and data access in your application. For example if you are using DLinq you will not have any new Sql features or anything, your database stays the same, but accessing the data and working with it becomes much easier. I personally do also like the fact that I don't have to write any Sql Commands anymore in C#. Sql is something for the database and using stuff like stored procedures. It was never fun to write your own wrapper everytime you have to access some database stuff. Lets see an example:

Before Linq:

Using SQL before Linq

With Linq:

Using SQL with Linq

Many more samples and examples can be found in the 101 LINQ Samples, which are still very useful.
ScottGu gave also a nice introduction about using LINQ with ASP.NET on his blog.

Also don't confuse LINQ (sometimes called C# 3.0 because it will come in Visual Studio 2007 - code name Orcas) with the Microsoft .NET Framework 3.0 (formerly known as WinFX), which consists of all the new Windows Foundatation technologies (WCF - Windows Communication Foundation (formerly Indigo), WPF - Windows Presentation Foundation (formerly Avalon), WF - Windows Workflow Foundation, Windows Cardspace (formerly InfoCard)). Ok, I admit you have every right to be confused.


Working with the new XDocument instead of XmlDocument

Ok, lets get back to Linq, we will talk about databases later. You might use some of the features in Linq in your classes, for example the new Extensibility Features, which are pretty cool to add functionality to existing classes. Other than that most of your code will stay the same, you will most likely not use queries just to render some lines on the screen.

But if you were using the XmlDocument class before, a lot of code can be changed and simplified. I had a couple of Xml helper classes, which I don't need anymore now since using the XDocument and XElement classes is much simpler than before with XmlDocument and XmlNode. Lets take a look how easy it is to compress large parts of code basically into a single line:

XmlDocument (.NET 2.0 and before):

XmlDocument before Linq

XDocument (Linq):

XDocument with Linq

Working with Xml data is also a lot easier now, check out the 101 Linq Samples to see what you can do with the new syntax in Linq. I would say code that is using Linq can get up to 2 to 3 times smaller than before if you use a lot of foreach enumerations and lists, especially in combination with xml data.


No schemas in Linq? What to do.

For some reason there is no XSchema class in Linq, but you can still use the existing XmlSchema class in the System.Xml.Schema namespace. Creating XElement nodes directly from XmlSchemas might require some new code, but it is not very hard to convert any old code. Lets take a look at a simple example.

Example Xsd Schema file (SomeSchema.xsd):

XmlSchema definition for Linq

Creating an XElement with help of a schema:

Creating an XElement with help of a schema

The helper method for filling the XElement node:

The helper method for filling the XElement node

The Linq documentation says you can also use Annotations instead of working with schemas to specify rules for your xml data, but in my case this doesn't help to create new xml data. To learn more about Annotations read the Linq documentation or listen to the Object Database Podcasts.


Using DLinq

Ok, all this Xml stuff is interessting, but most applications, especially websites store their data in databases and this is were DLinq becomes useful. DLinq was the main reason for me to even bother checking out Linq. I always hated to write SQL commands in C# (or any other language) and not be able to catch any obvious errors, which could be seen while coding if Intellisense would be available for SQL Commands. But even if all the syntax is correct, a lot of semantic errors can happen and only testing it 7 million times makes sure that it works. As seen above we can now write our own queries directly in C# with Linq, which will create some stored procedures in the background for us. These queries are only created if we write some select statement in C#, the data is not actually retrieved yet. Only if we call foreach to enumerate all users a sql command is created in the background and will be handled.
Using SQL with Linq
So what about that TestDb class, where does it come from? It is autogenerated with help of the SqlMetal command line tool in Linq. This tool will create a class for every table in your database and give you a database class (in my case TestDb) and some helper methods to access your data. Everything else can be done directly from C# code.

What about performance? Well, I'm no SQL guru and it is hard to tell if Linq performs well on big databases, but from my tests and experiences in the last weeks, there is nothing wrong with Linq. It performs quite well. I don't think it will be Linq's fault if your database access is slow. You can also write Stored Procedures (see next section) if you think you can write some better sql code and call it directly from Linq. I can tell you for sure that using Dlinq is much more enjoyable (even with the current Intellisense bugs with Linq) than writing SQL statements in C#, I hope I don't have to do that ever again.

When will Linq be available? Currently Linq is still in Beta, it will become available in the next Visual Studio Version (code-name Orcas), which will come in 2007. Until then a couple of new Beta versions might come out. Beta 2 (Linq May CTP) is pretty stable and useable, it has only a couple of issues with the Intellisense in VS.


Stored Procedures with DLinq

Maybe you have already a lot of SQL tables and some Stored Procedures around and just want them to work with DLinq. Just use the /sprocs command line switch for SqlMetal. Now a couple of helper methods will be created for you that allow you to execute these Stored Procedures directly and use the return value as you would with a query written directly in DLinq.

Sahil Malik wrote on his blog Winsmarts already a lot of info about DLinq and Stored Procedures, so I'm going to be cheap and just link to it :-)


Blinq

Thats not all. If you are usinq Linq for your website you should check out the Blinq Project, which automatically generates ASP.NET websites for all your database tables. It does not only allow you to view data, but you can also easily create new entries or change any data in the tables. If you know MyPHPAdmin from the php world, Blinq is quite similar (but not as complicated). Even if you don't really need this capabilities the generated code from Blinq can be helpful setting up your ASP.NET website because it shows how to use master pages, access your database and do all the things like getting data, adding data, updating tables, deleting rows, etc.

This is what a Blinq website looks like (ok, I've only created a very simple database):
Blinq TestTable


Linq Links


That's it for today, more this weekend, when I announce that I will play StarCraft - Broodwar on the german TV. Arg, this wasn't supposed to come out yet ... (grin)