Difference in LINQ Queries

I've been asked about the different contexts that data can be queried, which there is some.  With LINQ to SQL, when querying against the data context, there is limited support for what can be done with LINQ to SQL; this is because the parser evaluates your LINQ query and converts it to a query that can be used to retrieve data from the database.  This is why you can see the SQL generated from a query for testing purposes.  This is why in LINQ to SQL queries, you can't use your own custom methods and and other methods used as well (such as string.IsNullOrEmpty()).  So when the data is queried as such:

var customers =
  from c in this.Context.Customers
  where c.IsActive == true
  select c;

This data is translated into a query and fetches the data against the database.  The queried data returns in the form of a queryable set of customers.  This customer has reference to all foreign keys in the system, so if there is a related orders table, the customer class has an Orders collection of type EntitySet.  This collection is loaded in a deferred fashion (http://msdn2.microsoft.com/en-us/library/bb399393.aspx) but could be loaded immediately (see the end of that article, the article on LoadWith method).

However, once you have a set of data brought down from the database, you can use regular LINQ queries that can incorporate custom methods and the like.  This is the LINQ to Object side of LINQ where LINQ isn't translating your query into a database call.  This would work like any system; when you get the data, it's converted into business objects for a meaningful representation of your data, and you can transform or use it to your liking.  So something like this:

var orders = customer.Orders.Where(i => i.OrderDate.Year > 2000);

You could replace the query with custom methods or objects and can use it in this context:

var orders = from o in customer.Orders
                  where this.MeetsCriteria(o.OrderStatus)
                  select o;

So that is the difference.

Published Thursday, March 27, 2008 3:41 AM by bmains
Filed under:

Comments

# re: Difference in LINQ Queries

Saturday, March 29, 2008 8:33 PM by JoshC

Thanks for the post. I am still learning LINQ and all this helpful.

Josh Coswell

http://riverasp.net