Build Linq query on the fly

G

GiJeet

Hello, in SQL we can build a SQL query on the fly by appending strings
of commands then use the Exec() command to execute the query. Is
there a way to do the same with C# and Linq?

Thanks,
G
 
P

Pavel Minaev

Hello, in SQL we can build a SQL query on the fly by appending strings
of commands then use the Exec() command to execute the query.  Is
there a way to do the same with C# and Linq?

Yes, and in a far better way than appending strings - you get to work
directly with AST of the query. Look at the Expression<T> class, and
the associated Expression helper static class. All IQueryable
operations actually take Expression<T> instances - they're implicitly
created for you when you use lambdas or LINQ syntactic sugar, but you
can just as well build them yourself as needed.
 
G

GiJeet

Yes, and in a far better way than appending strings - you get to work
directly with AST of the query. Look at the Expression<T> class, and
the associated Expression helper static class. All IQueryable
operations actually take Expression<T> instances - they're implicitly
created for you when you use lambdas or LINQ syntactic sugar, but you
can just as well build them yourself as needed.

Thanks. Can you point me to some examples. I learn better by seeing
examples. Thanks.
 
P

Pavel Minaev

Thanks.  Can you point me to some examples.  I learn better by seeing
examples.  Thanks.

This is a general explanation of expression trees:

http://blogs.msdn.com/charlie/archive/2008/01/31/expression-tree-basics..aspx

This one is more detailed, and includes a brief sample on hand-
building them:

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

This one is a sample specifically covering your case (dynamic query):

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

Michael C

Pavel Minaev said:
Yes, and in a far better way than appending strings - you get to work

"Better" is a loaded word. It couldn't get much simpler than appending
strings. :)

Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top