views:

21

answers:

1

I have a very simple LINQ To Entities query as follows:

   var orderID = 1;
    var orders = (from o in db.Orders
                where o.OrderID == orderID
                select o).SingleOrDefault();

Can anyone tell me why this query wouldn't work? It doesn't even not throw an exception. I have also checked the SQL profiler and the above query does not even fire the corresponding SQL query. But when I directly plugin the value of the orderID into the query where o.OrderID == 1 then everything works fine.

A: 

Firstly, a much simpler query would be

var specifiedOrders = db.Orders.SingleOrDefault(o => o.OrderID == orderID);

Secondly, are you sure you query is not firing in sql? By default Linq will defer the query execution as late as possible. This means it will only execute a query when you call GetEnumerator or a similar operation on the query. However in your example the .SingleOrDefault() call should execute the query.

Check the following:

  1. The result of the query. What is the value of orders?
  2. If you execute this in Visual Studio, hover over db.Orders and check its value.
  3. Are you connecting to the correct database?
Jaco Pretorius