Friday, 30 January 2015

ASP.NET Tips #20 - Don’t call AsEnumerable on a collection before using LINQ

When you're using an ORM that has LINQ to SQL, such as Entity Framework, do not call AsEnumerable on the collection before using LINQ, even if that gives you options that are easier to work with.

If you do, it means your LINQ query is run at web server, rather than converted to SQL and performed on the database server.

Sample C# code:

//So we have this Car class
public class Car
{
  public string Make { get; set; }
  public string Model { get; set; }
  public int Year { get; set; }
  public string Color { get; set; }
}
//In some class or form or service that utilizes this process...
//this method has all the plumbing inside to fill and return a dataset
DataSet dataSet = _dataBase.ExecuteDataSet("sproc_GetMeSomeCarData");
DataTable dataTable = dataSet.Tables[0];

//Now call the new extension passing the Car object for less cumbersome, normalized LINQ-to-Object syntax
var nissanCars = from c in dataTable.AsEnumerable()
                 where c.Make == "Nissan"
                 select c;

No comments :

Post a Comment