0

I want to build an IQueryable query from a string (it would come from a table). The reason I want the IQueryable is I want to use OrderBy, Take and Skip to do paging. I'm using Entity Framework with DBContext so I looked at Entity SQL but it looks like its restricting the query to a class.

What I want to do is:

string sql = GetQueryFromDatabase();
IQueryable q = PerformMagicToMakeStringIQueryable(sql);
q = q.OrderBy(somefield).Skip(5).Take(10);

From there I'm good, I know how to find out what fields are in the query and do what I need.

Ideas?

thanks,

john

John Mott
  • 445
  • 6
  • 12
  • 1
    Don't believe you can do that without some kind of ORM. Might have a look at [building an iqueryable provider](http://blogs.msdn.com/b/mattwar/archive/2007/07/30/linq-building-an-iqueryable-provider-part-i.aspx) – Brad Christie May 13 '15 at 01:09
  • Thank you. That would imply that parsing the SQL string to build the expression tree would be necessary. Is there convenient code to build a linq expression tree from a T-SQL statement? – John Mott May 13 '15 at 03:42
  • Not that I'm aware. You're usually doing the inverse (LINQ-to-SQL) which targets databases based on the connector (targetted DMBS connector) – Brad Christie May 13 '15 at 03:44
  • Just thinking out loud really, but instead of storinq sql as a string, could you store an expression tree as a string? First result I got on a google search is here: http://stackoverflow.com/questions/217961/serializing-and-deserializing-expression-trees-in-c-sharp – Colin May 13 '15 at 07:55
  • Supporting OData Query Options in ASP.NET Web API 2 with EF [msdn](http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options) – Eldho Jul 03 '15 at 11:26

1 Answers1

1

There's a thing called DynamicLinq which you can use.

There are lots of different versions as MS released the original as source code and it's been modified a gazillion times:

Here's one with docs:

http://dynamiclinq.azurewebsites.net/

Here are the others:

https://www.nuget.org/packages?q=dynamic+linq

mcintyre321
  • 12,996
  • 8
  • 66
  • 103