Convert string to linq query

I played with LINQPad, and I was curious how I can implement this behavior in my own application, namely: how can I allow a user to enter a LINQ query into a known database context as a string, and then run this query in the application?

For example, if I have a LINQ-to-SQL datacontext for the Northwind database in my application, I want the user to be able to enter

from cust in Customers
where cust.City == "London"
select cust;

And I will return the results of the .ToList () call in this query.

Any ideas / tips / links?

Thanks, kindly

Mustafa

+3
source share
4 answers

The namespace System.CodeDomcan do what you are looking for. Check out this blog post:

http://blogs.msdn.com/lukeh/archive/2007/07/11/c-3-0-and-codedom.aspx

public static void Main , DataContext IEnumerable, LINQ. - .

, , , , , . ; , .

, , , . .

+4

, LINQPad , .NET Reflector (LINQPad ). :

, .

, .

+3

"Snippy", "# in depth" . -. "Snippet.cs" 130 " ".

+1

, , , , . :

:

from cust in Customers
where cust.City == "London"
select cust;

If you want to dynamically change Lquery, not cust.City == "London", to cust.Street == "London". You should use the if-else statement as follows:

var lquery = (from cust in Customers
where cust.City == "London"
select cust).ToList();

if(true){
 lquery = (from cust in Customers
where cust.Street == "London"
select cust).ToList();
}

GridView.DataSource = lquery;
GridView.Databind();

The code above is longer than your code, but it can satisfy your theme. In my project, I still use this code because it does not delay my program, but it executes my current problem.

0
source

Source: https://habr.com/ru/post/1727679/


All Articles