After publishing the blog article on Mocking in EF 2.0, Diego Vega (Microsoft Program Manager Entity Framework and LINQ to SQL Product Teams in Redmond) pointed out that the following code snippet is quite inefficient:


    var customers = (from cus in _context.Customers
                    where cus.CustomerID == i_customerId
                    select cus);
    if (customers.Count() == 1)
    {
        o_customer = customers.Single<Customer>();
    }
    else
    {
        o_customer = null;
    }

It turns out that even though the expression does not change between the call to customers.Count() and customers.Single<Customer>(), they will actually cause two calls to the Database. I had mistakenly assumed that the result would be cached as there was no change to the “query”.

By using the SingleOrDefault<T>() function that is now available in EF 2.0 (through IQueryable<T>) we actually save on the round trip.


    o_customer = (from cus in _context.Customers
                    where cus.CustomerID == i_customerId
                    select cus).SingleOrDefault<Customer>();

Something to bear in mind when working with IQueryable<T>.

a2dbm5vn79

  • Share/Bookmark

One Comment

  1. Alec says:

    Nice one, thats helped. Thanks

Leave a Reply