473,757 Members | 6,899 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

LINQ to SQL ad hoc filter with where clause

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 data
that would be used to filter the dataset we return. STANDARD STUFF.

Below is simplified version (not compete) of how we solved this with
ADO using javascript on the client to build a where clause that we
would use on our SQL SELECT statement.

//build SQL statement with element values - % means don't add to
select statement
MyForm.SQL.valu e = "Select DISTINCT XMID, Description, RecordType,
TagDesc, SZGROUPNAME, KSZTAG, VENDOR_NAME, DEVICE_NAME,KSZ SERIALNUM
from " +
FromClause + " Where ("

// Partial Tag
if (MyForm.TagPref ixes.value != "%"){
MyForm.SQL.valu e = MyForm.SQL.valu e + "SubString(KSZT AG,1,3) = '" +
MyForm.TagPrefi xes.value + "' And ";
lRetVal = true;
}

// Transmitter Vendor
if (MyForm.Manufac turers.value != "%"){
MyForm.SQL.valu e = MyForm.SQL.valu e + "VENDOR_COD E = " +
MyForm.Manufact urers.value + " And ";
lRetVal = true;
}

// Transmitter Model
if (MyForm.ShortMo dels.value != "%"){
MyForm.SQL.valu e = MyForm.SQL.valu e + "Substring(DEVI CE_NAME,1,4) =
'" + MyForm.ShortMod els.value + "' And ";
lRetVal = true;
}

// Group
if (MyForm.Groups. value != "%"){
MyForm.SQL.valu e = MyForm.SQL.valu e + "WGROUPCODE = " +
MyForm.Groups.v alue + " And ";
lRetVal = true;
}

// Span - Range
if (MyForm.RangeUn its.value != "%"){
MyForm.SQL.valu e = MyForm.SQL.valu e + "(RRANGELOW ER >= " +
MyForm.LRange.v alue + " And " +
"RRANGEUPPE R <= " + MyForm.URange.v alue + ") And ";

// Units
MyForm.SQL.valu e = MyForm.SQL.valu e + "UNIT_NAME = '" +
MyForm.RangeUni ts.value + "' And ";
lRetVal = true;
}

As you can see we are just building a string depending on whether the
user chose a particular piece of data to use in the filtering. We
would then pass this SQL "statement" to our .asp page in a POST and
run aqainst the data connection.

Is it possible to build a where clause somehow using LINQ to SQL on
the fly? I am new to LINQ, and have seem mostly simple examples of
filtering with LINQ. The LINQ I need to run would look something
like:

CStoneDataConte xt cs = new CStoneDataConte xt();
var query = from q in cs.CalServices
where q.VENDOR_CODE ==
Convert.ToInt16 (ddlVendor.Sele ctedValue)
select new
{
q.XMID,
q.KSZTAG,
q.Description,
q.SZGROUPNAME,
q.VENDOR_NAME,
q.DEVICE_NAME,
q.KSZSERIALNUM
};

grdInstList.Dat aSource = query;
grdInstList.Dat aBind();

However I need to make the where clause dynamic so I can build it
depending on the user's choices. Any ideas, anyone?

Thanks
Aug 6 '08 #1
6 4169
Holy SQL Injection Batman! Building SQL in javascript at the client is
generally a very bad thing to do...

Re the LINQ aspect, you can compose (i.e. combine) LINQ queries like so:

IQueryable<CalS ervicequery = cs.CalServices;

if(name != null) { // string
query = query.Where(s=> s.Name == name);
}
if(activeOnly) {
query = query.Where(s=> s.IsActive);
}
if(deciveName != null) {
query = query.Where(s=> s.DeciveName == deviceName);
}
//..etc

You can do more powerful things, but you'd need to give a more specific
question. There is a "dynamic LINQ" sample available as well (for
parsing queries as strings into LINQ expressions).

Marc

Marc
Aug 6 '08 #2
Oh, I forgot to add - you can still do the anon-type at the end:

.... previous post ...

var actualQuery = from q in query
select new {... anon type ...};

and use actualQuery for the data-bind. I would also recommed doing any
processing outside of the query, as it is hard to predict what will get
done immediately vs inside the query - for example:

var query = from q in cs.CalServices
where q.VENDOR_CODE ==
Convert.ToInt16 (ddlVendor.Sele ctedValue)

I would write as:

short vendorCode = Convert.ToInt16 (ddlVendor.Sele ctedValue);
var query = from q in cs.CalServices
where q.VENDOR_CODE == vendorCode

These two formations can actually works very differently (or one works,
one doesn't) under some circumstances.

Marc
Aug 6 '08 #3
On Aug 6, 1:18*pm, Marc Gravell <marc.grav...@g mail.comwrote:
Oh, I forgot to add - you can still do the anon-type at the end:

... previous post ...

var actualQuery = from q in query
* * * * * * * * * select new {... anon type ...};

and use actualQuery for the data-bind. I would also recommed doing any
processing outside of the query, as it is hard to predict what will get
done immediately vs inside the query - for example:

* var query = from q in cs.CalServices
* * * * * * * * * * * * *where q.VENDOR_CODE ==
Convert.ToInt16 (ddlVendor.Sele ctedValue)

I would write as:

short vendorCode = Convert.ToInt16 (ddlVendor.Sele ctedValue);
var query = from q in cs.CalServices
* * * * * * * * * * * * *where q.VENDOR_CODE == vendorCode

These two formations can actually works very differently (or one works,
one doesn't) under some circumstances.

Marc


Thanks Marc,

SQL Injection is not the big boogey man for us, all this is on an
intranet, very secure inside a hardened firewall.

Good info, looking at examples I thought I would need to do
the .Where() method, just couldn't seem to get started on it. Nice
boost...

Aug 7 '08 #4
SQL Injection is not the big boogey man for us, all this is on an
intranet, very secure inside a hardened firewall.
Yes, because people "on the inside" would *never* abuse a system....

Marc
Aug 7 '08 #5
On Aug 7, 11:06*am, Marc Gravell <marc.grav...@g mail.comwrote:
SQL Injection is not the big boogey man for us, all this is on an
intranet, very secure inside a hardened firewall.

Yes, because people "on the inside" would *never* abuse a system....

Marc
If you only knew. Outside this office I doubt if there are 2 other
people here who even know what SQL injection is much less how to pull
it off :-)

Good info on the processing (short vendorCode =
Convert.ToInt16 (ddlVendor.Sele ctedValue);
var query = from q in cs.CalServices
where q.VENDOR_CODE == vendorCode )

did not realize that using the Convert (or others) in the LINQ would
cause problems
Aug 7 '08 #6
did not realize that using the Convert (or others) in theLINQwould
cause problems
It isn't a "would" - it is a "could"; both with this and you other
(direct e-mail) question, it depends hugely on the provider. LINQ-to-
Objects, for example, will work with delegates, and it won't matter
much* either way. But if the provider is using query expressions
("Expression ") instead of lambdas, then it depends entirely on what
the provider supports. For example, some string operations will work
(including Substring usually), but others (such as overloads accepting
a specific culture) won't - either because the notion of different
cultures makes no sense for that provider (most database engines have
a fixed culture per db), or because it simply hasn't been implemented
(every operation takes work to translate - not everything is supported
by every provider).

Marc

*=give or take some subtleties about "captured variables" and mutating
the variable after query construction but before execution...

Aug 8 '08 #7

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

Similar topics

2
720
by: Zygo Blaxell | last post by:
I have a table with a few million rows of temperature data keyed by timestamp. I want to group these rows by timestamp intervals (e.g. every 32 seconds), compute aggregate functions on the columns, and ultimately feed the result into a graph-drawing web thingy. I'm trying a few different ways to get what seems to be the same data, and seeing some odd behavior from the query planner. The table looks like this:
2
2183
by: The Other Mike | last post by:
VS 2005 Is their a way to dynamically change the where clause in a datagridview or dataset? I have a search window where the user can enter a part number or description or customer etc... and would like to change the where clause based on what the user has filled out.
2
10598
by: Rob Dob | last post by:
Hi, in the old days, pre .Net 2.0 I could just modify the SQLCommand of the SQlDataAdapter to reflect a different where clause and then issue a .Fill(), and Whamo!!! everything worked.. How am I to accomplish the same task using ..NET 2.0 and the NEW "TableAdapter", I can't see myself creating 100's of Queries using the wizard, is there anyway for me to just change the sql Where clause at runtime? I have the TableAdapter bound to a...
6
10905
by: Altman | last post by:
I am playing around with making a dataset with the designer in vb.net 2005. I realize you can add parameters to select statement and then filter off of those parameters. What I would like to do is to take the dataset that the designer made and add the whole where clause to it at run time. Is this possible?
8
3481
by: chrisdavis | last post by:
I'm trying to filter by query or put those values in a distinct query in a where clause in some sort of list that it goes through but NOT at the same time. Example: ROW1 ROW2 ROW3 ROW4 , etc. I want to go to the first row, do a WHERE statement, return the
0
13756
NeoPa
by: NeoPa | last post by:
Intention : To prepare a WHERE clause for multiple field selection, but to ignore any fields where the selection criteria are not set. ONLY WORKS WITH TEXT FIELD SELECTIONS. Scenario : You have a table (tblMember) containing information for various people. Table Name=tblMember Field; Type; IndexInfo MemberID; AutoNumber; PK Surname; String
0
5018
by: Jay Douglas | last post by:
Hello, I've found some posts on creating dynamic WHERE clauses in LINQ to SQL using predicate builders and extending lamda expressions. One issue with these posts is all the examples only use a single customer table. I'm need a way to dynamically create a where clause using multiple tables. None of the tables I'm using have references in the LINQ designer so the JOIN operator is required. If I were to hard type out the query in...
12
25128
by: =?ISO-8859-1?Q?Ren=E9?= | last post by:
Hi, is there a rule of thumb what is better/faster/more performant in SQL Server 2005? a) SELECT * FROM A INNER JOIN B ON B.ID = A.ID AND B.Cond1 = 1 AND B.Cond2 = 2 b) SELECT * FROM A INNER JOIN B ON B.ID = A.ID WHERE B.Cond1 = 1 AND B.Cond2 = 2
10
2109
by: Qtip23 | last post by:
Hello All, I am unable to get my VBA code to show all the records and allow me to view the filtered responses from user input, once my cmd_click() event fires. The form displays the 19 fields from database in an AD HOC form, using a
0
9298
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10072
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9906
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9885
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9737
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6562
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.