Welcome to EMC Consulting Blogs Sign in | Join | Help

Anthony Steele's Blog

Linq to SQL: testing, the long way around

Linq to SQL is great. You can open up your Db schema, drag some tables in, and in no time you have a data context class with loads of functionality, and data classes for all of the entities. No more recordsets to unpack into objects, no more fields to pack into SQL params, just lists of strongly typed ojects. Even better, the classes are partial so that you can extend them.

It seems natural to extend the data context by adding methods like
var orders= MyDataContext.GetOrdersForCustomer(myCustomer.Id);

Methods like these are trivial to implement with Linq:

from o in orders where o.CustomerId = customerId select o;

And Linq makes persistence simple too. 

Now the problem comes in when you think about layering and mocking. You'd like to have a interface e.g. "IDataStore", with an implementation of it that is backed by the database, and another mock implementation for testing. You'd like to have the data classes to be defined where they depend on neither of these implementations, but both implementations can reference them.

But Linq to SQL's code isn't laid out like this if you drag and drop. The DataContext doesn't implement any interfaces. The data classes are defined in the same namespace as the DataContext. You can test the data classes by just creating and populating them, but you can't test anything that depends on data retrieval without using the datacontext and behind it, the database.

It's taken me a while to get there, but this seems to be the problem that Ian Cooper is solving in Architecting LINQ To SQL Applications, part 5

Hence the"long way around" to seeing why Ian was on about that. Linq to SQL can be used in other ways besides drag and drop, and some of these ways will give you what you want.

Published Thursday, July 24, 2008 12:54 PM by Anthony.Steele
Filed under: , , , , ,

Comments

No Comments
Anonymous comments are disabled

About Anthony.Steele

Programmer in c# for Conchango

This Blog

Syndication

Powered by Community Server (Personal Edition), by Telligent Systems