Sunday, February 22, 2009

Linq extensions missing

I recently had a project to do using the new Microsoft Entity Framework, which gave me a serious bit of head scratching to do. The problem was that I had created a model as usual and created a controller class as usual; however compiling the code below gave me the error:

'System.Data.Objects.ObjectQuery' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'System.Data.Objects.ObjectQuery' could be found (are you missing a using directive or an assembly reference?)


public object GetSuppliers()
{
ObjectQuery supplierQuery;
using(NorthwindEntities northwindContext = new NorthwindEntities())
{
supplierQuery = northwindContext.Suppliers;
}
return supplierQuery.ToList();
}


WTF? Hang on I've used code like this dozens of times before and never got this error before. It took quite a time for me to figure out that when the class was created by Visual Studio it had failed to add the usual using System.Linq; line at the top.

This lead me to think, why this was the case and I found this interesting article which describes extension methods.

Simple once you know the answer.