473,378 Members | 1,364 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

LINQ: How to build dynamic query?

Hello,
played a little with orcas and went into a problem by building dynamic
queries. I want to build a dynamic where clause but only with parameters that
are not empty =(TextBox.Text != "").
Doing this by building a string is very simple, but how to do it with LINQ?

string sql = "";
if (TextBox1.Text != "")
sql += "Columns_1='"+TextBox1.Text+"'";
if (TextBox2.Text != "")
sql += "Columns_2='"+TextBox2.Text+"'";
How to include the if query to linq???

var query = from c in db.MyTable
where c.Column_1 == TextBox1.Text &&
c.Column_2 == TextBox2.Text
select c;

Thank you!

-Stefan
Nov 14 '07 #1
11 13633
(slightly simpler):

if (!string.IsNullOrEmpty(inputA)) {
query = query.Where(x =x.PropertyB == inputA);
}
if (!string.IsNullOrEmpty(inputB)) {
query = query.Where(x =x.PropertyB == inputB);
}

Marc
Nov 14 '07 #2
[watch for typo - should have been PropertyA]
Nov 14 '07 #3
It's actually slightly easier than that if you ignore the query
expression syntax:
...
Query expression syntax is nice in many cases, but just to add a
"where" clause I prefer to use the direct method call.
Yes - I posted that right after my initial post (albeit with a
typo)... I agree.
You could even write a method to abstract it out if necessary.
Care to expand on this? I can think of a few ways of interpreting
this, but I'm just interested in how you mean it...?

Marc

Nov 14 '07 #4
On Nov 14, 10:19 pm, Marc Gravell <marc.grav...@gmail.comwrote:
You could even write a method to abstract it out if necessary.

Care to expand on this? I can think of a few ways of interpreting
this, but I'm just interested in how you mean it...?
Well, you could have (off the top of my head - apologies if
Predicate<Tshould be Func<T,bool>)
(Further apologies for the formatting - Google groups uses a
proportional font)

IQueryable<TConditionalWhere<T>(static this IQueryable<Tquery,
string value,
Expression<Predicate<T>predicate)
{
if (!string.IsNullOrEmpty(value))
{
return query.Where(predicate);
}
}

then call it with:

var query = query.ConditionalWhere(valueA, x =x.PropertyA==valueA)
.ConditionalWhere(valueB, x =x.PropertyB==valueB);

Jon
Nov 15 '07 #5
You could presumably put an expression tree and lambda together
through code (using Expression.Property(...) at some point), but it
wouldn't be pretty. The switch would be easier to maintain.

Marc
Nov 15 '07 #6
Maybe it will work over reflection?
See my other reply
but in Windows.Forms this should
be not a problem.
winform is easy to abuse too... at least with ASP.NET the user doesn't
tend to have a direct connection to the database...

Marc
Nov 15 '07 #7
You could presumably put an expression tree and lambda together through
code (using Expression.Property(...) at some point), but it wouldn't be
pretty. The switch would be easier to maintain.
Some columns in my winform datagridview are defined by user in runtime.
So I cannot use hard-coded swith with all column names.

My grid columns can be string, bool and decimal types only.
Maybe it is possible to use switch for types only like

swith (SortExpression.GetTypeCode) {
case TypeCode.String:
....

case TypeCode.Bool:
...

case TypeCode.Decimal:
....

default:
MessageBox.Show("Cannot sort by this column");
}

Andrus.
Nov 15 '07 #8
There is an Expression.Property method (IIRC) that pairs to memberof;
I'll see what I can find...
Nov 16 '07 #9
Another question; the bit that you need to comment isn't clear, since
you don't actually change "query" with the comparer - query is still
"db.Klients"; is there a bit missing that might contain the glitch? It
may be unrelated, but it will be easier to investigate if you post the
verbatim code that isn't working...

Marc
Nov 18 '07 #10
Would it be possible for you to post the /generated/ code? Are you
familiar with "Reflector"? If you compile the *working* code
(x=>x.Nimi) and load it into Reflector, we could have a look at what
it generated? I should then be able to compare this to what the
dynamic code uses...

Unfortunately without runnable code this isn't something I can do
directly... but it has piqued my interest...

Marc
Nov 19 '07 #11
Would it be possible for you to post the /generated/ code? Are you
familiar with "Reflector"?
If you compile the *working* code
(x=>x.Nimi) and load it into Reflector, we could have a look at what
it generated? I should then be able to compare this to what the
dynamic code uses...
Generally No. I desided to download reflector sometime.
However before downloading it asks my personal data.
So I hit Cancel and did'nt download it.
I can study reflector if you need.
Unfortunately without runnable code this isn't something I can do
directly... but it has piqued my interest...
I sent test case to you by e-mail.

Andrus.
Nov 20 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
by: Marc Gravell | last post by:
In Linq, you can apparently get a meaningful body from and expression's .ToString(); random question - does anybody know if linq also includes a parser? It just seemed it might be a handy way to...
4
by: BeSharp | last post by:
I recently stumbled across a pretty interesting LINQ to SQL question and wonder, whether anybody might have an answer. (I'm doing quite some increasing LINQ evangelism down here in Germany.). ...
15
by: EDBrian | last post by:
My problem is this. Our clients create different fields they want to collect and we allow them build dynamic filters, reports etc... We run some TSQL to actually create the column and all works...
1
by: john | last post by:
I'm trying to build a LINQ expression that will use a dynamic construction of a LIKE statement in the WHERE clause, it would look something like this in SQL: WHERE TaskGroup Like "*00*" OR...
2
by: Joey | last post by:
I am querying a DataSet with LINQ. I am running into a problem when trying to construct my query because in the "from" clause I do not know the table name (range variable) until runtime. Possible...
6
by: Plissskin | last post by:
I need to create an "ad-hoc" filtering page in a web app we are building. The page would display a number of drop down lists, text boxes, and radio lists and allow the user to select (enter) some...
9
by: Cirene | last post by:
I'm about to begin a brand new, big, ASP.NET project (using 3.5 .net fw), VS 2008. I'm using MySQL as the backend (customer request.) I have absolutely no experience with LINQ and/or the Entity...
2
by: giddy | last post by:
hi, Yes its a design question again. =) If I have something like: class Person { //functions: static Person GetAllPersons(); static Person Search(string field,string value);
2
by: Colin Han | last post by:
Hi, all, If I write follow code in c# method. The IDE will compile it to a complex construct method of System.Linq.Expression. Expression<Func<int>ex = () =10; will be compile to:...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.