views:

178

answers:

1

I'm just getting started with EF and a query like the following strikes me as odd:

var departmentQuery =
                schoolContext.Departments.Include("Courses").
                OrderBy("it.Name");

Specifically, what sticks out to me is "it.Name." When I was tooling around with LINQ to SQL, pretty much every filter in a query-builder query could be specified with a lambda, like, in this case, d => d.Name.

I see that there are overrides of OrderBy that take lambdas that return an IOrderedQueryable or an IOrderedEnumable, but those obviously don't have the Execute method needed to get the ObjectResult that can then be databound.

It seems strange to me after all I've read about how lambdas make so much sense for this kind of stuff, and how they are translated into expression trees and then to a target language - why do I need to use "it.Name"?

A: 

Hey,

I get lamdba expressions with mine; I can do Where (it.SomeProperty == 1)... do you have System.Linq as a namespace? You can try restructuring as:

var departmentQuery = from d in schoolContext.Departments.Include("Courses") orderby d.Name select d;

Those are some possibilities.

HTH.

Brian
Interesting. I see that you're right in that it still works - I just need to set the DataSource of my GridView to departmentQuery instead of departmentQuery.Execute(MergeOptions.Whatever), because it's now an IQueryable or IOrderedQueryable instead of an ObjectQuery and so it doesn't have an Execute method. That being the case, it appears that I'm missing out on setting the MergeOption. I'm assuming that it just uses the default in this case?
nlawalker
Well even with IQueryable you should be able to use the lambdas; as long as its the generic form, otherwise you need to call Cast<EType>() on the collection to get it to the generic type. This may use LINQ to objects instead of L2E though. IQueryable is the interface and is implemented by ObjectQuery too, FYI.
Brian
What I'm saying is that using a lambda in something like Where or OrderBy returns you an IQueryable, *not* an ObjectQuery. Try calling Where on an ObjectSet or ObjectQuery and look at the overloads with Intellisense - the ones that take Expression<Func<>> return an IQueryable and the ones that take a Func<> return an IEnumerable. The only way to get an ObjectQuery back is to call the overload that takes (string, params ObjectParameter[]).All that said, I'm now seeing that you can cast back to an ObjectQuery and regain access to Execute(). Marking as answer for the helpful chat, thx.
nlawalker
Hey, thanks for that. Additionally; IQueryable is an interface, but the actual type could be any; to experiment, get the IQueryable back and do: if (query is ObjectQuery<T>) to see if the underlying result is an object query. Additionally, what is the need to have an ObjectQuery? To have access to the execute method?
Brian