Sep 05

First thoughts on LINQ To SQL

Posted in C# LINQ      Comments Off on First thoughts on LINQ To SQL

In these last couple of days I’ve also been busy looking at LINQ To SQL. By now, I’m able to have some opinions on it. First, the things I liked the most…LINQ To SQL is PI (ie, Persistence Ignorant) which is great (at least, that is what I think). This means that your classes won’t have to inherit from any specific class or implement some interface, so you can build your own POCOs.

Getting POCOs means that you won’t have to use the EntityRef<T> and EntitySet<T> classes, but it also means that you won’t get lazy loading (which you get by default when you use those classes for setting up your associations). Ok, you can solve this easily by using the DataLoadOptions class and making sure that you’re getting all the associated objects in one go. Problem solve, though I can see many complaining about this…

One of the things that isn’t required but that will improve performance is implementing the INotifyPropertyChanged interface. As I said, you can get away without implementing this interface, but the tracking service used by the DataContext won’t be able handle the PropertyChanging event which means that it’ll have to copy all the properties after an object has been attached to that context.

By the way, there’s one thing I didn’t really like: detaching and attaching objects to contexts sucks big time. I’ve had a graph of objects loaded from a context and I wanted to persist its changes by using another context. This isn’t as simple as you might think,specially if you have private/internal EntityRef<T> or EntitySet<T> properties/fields. In those cases,you need to clean those elements or you end up getting an exception. You can get more info about that here (I’ve just been playing with it, but haven’t really had the time to investigate its internals).

As you might expect, you can also build your database from your domain model since the DataContext class exposes a method called CreateDatabase which is responsible for doing that. This is great and means that I can (sort of!) concentrate on my domain model and then build the db from it. Oh, and I almos forgot the thing I loved most about it: being able to use LINQ expressions is really really cool.

Final note to the SQL Metal (I believe this is the name) tool which you can use to generate your classes: don’t use it unless you have to. You’ll end up with an anemic model, full of things that you shouldn’t need!

I’ll be playing more with LINQ To SQL and I’ll have more to say about it in the next days…