views:

188

answers:

2

Hi All

I have been trying to use dynamic LINQ to Entity in my application for specifying the OrderBy attribute at runtime. However when using the code as described in the majority of documentation:

var query = context.Customer.OrderBy("Name");

I received the following exception:

System.Data.EntitySqlException: 'Name' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly.

After much searching I found this MSDN page:

http://msdn.microsoft.com/en-us/library/bb358828.aspx

Which included the following code example:

ObjectQuery<Product> productQuery2 = productQuery1.OrderBy("it.ProductID");

This prompted me to change my code to the following:

var query = context.Customer.OrderBy("it.Name");

After this the code works perfectly. Would anyone be able to confirm that this is indeed the correct way to get OrderBy working with LINQ to Entity? I can’t believe that the framework would have been implemented in this way, perhaps I have overlooked something?

Thanks, Matt

A: 

No nice way, so far

My answer to this question was to create a stored procedure which has parameter to control sorting.

Sergey Osypchuk
+1  A: 

The it.Name syntax is ESQL and is indeed specific to the EF. There are good reasons to use this sometimes (e.g., collation specifiers), but it's not what I normally do.

Usually I use standard LINQ expressions:

var query = context.Customer.OrderBy(p => p.Name);

You can also use System.Linq.Dynamic, if you download it from Code Gallery, and then your original query:

var query = context.Customer.OrderBy("Name");

...will work.

Craig Stuntz
Thanks, I'll try the dynamic lib and see if that works. Would you be able to provide an example when it would be preferable to use the 'it' syntax? It seems to tightly couple your code with an implementation that you have no control over. I.e. it might change and thus break your code?Thanks, Matt
Matt
IMHO, the only good reason to use ESQL over System.Linq.Dynamic is if you need to use one of the few features in ESQL which are unavailable in S.L.D., such as collations. Mostly I prefer S.L.D.
Craig Stuntz