I just had an interesting conversation with the co-editor of this blog which went something along the lines of…

BigMart: I haven’t had chance to dig into LINQ properly but I don’t like it

Me: But delayed execution rocks (follow long rambling explanation)

BigMart: For our next project I won’t be using that MVC rubbish

Me: But it rocks!

OK I’m paraphrasing and neither of us actually talks like that. However it did get me thinking about my willingness to follow the pack (people like Rob Conery ;-)) when it comes to these kind of developments.

I’m not entirely sold on the approach Rob has taken with his MVC storefront app, but then it seems neither is he, however there’s a lot in there that I like.


I’m new to LINQ (specifically LINQ2SQL) and at first couldn’t see any reason to use it over Subsonic. However then I delved into the Storefront app a bit more and I can see why Rob’s drawn to it.

Take a simple address query…

   1: public IQueryable<Address> GetContacts()
   2:         {
   3:             return (from address in _db.Addresses
   4:                     select new Address
   5:                                {
   6:                                    Id = address.AddressId,                                   
   7:                                    CompanyName = address.CompanyName,
   8:                                    StreetAddress = address.StreetAddress,
   9:                                    CityTown = address.CityTown,                               
  10:                                    PostCode = address.PostCode,
  11:                                });
  12:         }

Address is a simple class with several properties.

   1: public class Address
   2: {
   3:     public int Id { get; set; }
   4:     public string CompanyName { get; set; }
   5:     public string StreetAddress { get; set; }
   6:     public string CityTown { get; set; }
   7:     public string PostCode { get; set; }      
   8: }

The key thing to note about this is that nothing gets executed until we actually try to do something with this function. Calling GetContacts() won’t execute any SQL until we try to do something with it (like retrieve a generic list for example).

Why is this important? Well it means that you can further refine your query before executing it.

Lets say the above method is in a class called SqlContactRepository and now we’re going to write some business logic to deal with addresses.

   1: public Address GetAddress(int addressID)
   2:         {
   3:             var address = (from a in _repository.GetContacts()
   4:                            where a.ContactDetailsId == addressID
   5:                            select a);
   7:             return address.SingleOrDefault();
   8:         }

This code looks for a specific address (by Id in this case) and then returns it. Because of delayed execution nothing will touch our database until we call


So what have we achieved? Well we have a nice simple repository which maps our database to our model (address).

We then have a higher level Service which can retrieve the IQueryable object, query it some more and then eventually execute the sql and grab the result directly into our model.

If we need a list (rather than a single object) we can simply do the following…

   1: public List<Address> GetAddresses(string city)
   2: {
   3:     var addresses =  (from a in _repository.GetContacts()
   4:                       where a.CityTown == city
   5:                       select a);
   7:     return addresses.ToList();    
   8: }


Throw MVC into the equation and things get really interesting. Now we have a simple Contacts Service which returns a generic list of addresses. Its simple to write an MVC controller to retrieve the data and pass it to a view.

   1: public ActionResult AddressSearch(string city)
   2: {
   3:     return View("AddressSearchResults", _service.GetAddresses(city));
   4: }

Approaching all of this with interfaces (IContactRepository, IContactsService) you can easily write unit tests from the repository right the way up to the controller. Everything is loosely coupled, you can swap your repository out at any time (as long as you continue to return IQueryable objects to the service).

That said there are frustrations with this approach (as Rob has also identified). My own personal concerns lie around…

  • Responsibilities – deciding where to put the business logic (its easy for the Service and Repository responsibilities to become muddled)
  • Mocking – I prefer to use a mock framework (e.g. Rhino Mocks) for unit testing and mocking IQueryable is tricky, you tend to end up having to use test repositories instead

So what’s the conclusion? Well firstly I really like ASP.NET MVC. Even in this simple example it’s clear that I don’t have to worry about the presentation logic whilst I’m developing the main business logic. Add to that the fact that I can easily unit test right up to the controller level and I’m sold on it.

LINQ clearly has some major plusses in terms of its delayed execution and mapping to custom objects. The SQL generated is generally fine and I’ve not run into any performance concerns (yet).

Overall only time will tell but so far I think MVC 1.0 (whenever it’s released) and LINQ will be a viable solid basis for a robust Web App.

  • Martin Evans

    Hey Jon, I didn’t want to comment until I had dug into LINQ a little more and could give you a half decent reply.I’m just starting to realise the benefits of LINQ and think it does indeed rock. There I said it.However, I personally think the big wins for it are the extra features it brings to the C# language. For example, the other day, I wrote an extension method that enabled me to discard an entire decorator class! Its quite interesting to see how LINQ has evolved based on the introduction of Generics in version 2.0 of the .NET framework but I’m concerned that the the line between functional and imperitive features of C# will become more and more hazy(?) and that the language will become more complex.I’ve used Linq to SQL and think its ok but I see persistence issues as secondary these days to object interaction and understajnding design patterns. That said, I’m looking forward to get the chance to grok up on ADO EF and Linq To Entities (when I can) as I can see that lighting up my life…

  • MrTea

    Entirely with you on the “persistence issues as secondary” bit.Out of interest, how are exposing access to your persistence layer?I’m generally leaning towards a loose interpretation of the Repository pattern nowadays with a simple Repository Interface which exposes data as generic lists, or (for updates/inserts) accepts objects as arguments to functions.A (Rob Conery inspired) variation being to expose the data as IQueryable (exploiting the benefits of delayed execution)

  • Just reading this again, it’s funny how things change (especially in the super fast world of programming).

    I’ve almost completely dumped Linq2Sql in recent months. I hit too many issues with the black magic surrounding data contexts and change tracking to be entirely comfortable with it as my persistence layer.

    That said, I haven’t yet settle on an alternative. I’m a fan of Subsonic, but must confess that I get stuck somewhere between using Active Record, and trying to use Linq for my queries.

    I’ve also dabbled with NHibernate and can see a lot of potential here (especially when using Fluent NHibernate to cut down on boilerplate mapping files).

    The biggest change in my approach though is around Command Query Separation. I am increasingly of the opinion that data queries should be screen specific and optimised for speed, whilst commands (update, add etc) should go through an intelligent domain model and be persisted via an ORM (such as NHibernate).