473,387 Members | 1,536 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,387 software developers and data experts.

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.value = "Select DISTINCT XMID, Description, RecordType,
TagDesc, SZGROUPNAME, KSZTAG, VENDOR_NAME, DEVICE_NAME,KSZSERIALNUM
from " +
FromClause + " Where ("

// Partial Tag
if (MyForm.TagPrefixes.value != "%"){
MyForm.SQL.value = MyForm.SQL.value + "SubString(KSZTAG,1,3) = '" +
MyForm.TagPrefixes.value + "' And ";
lRetVal = true;
}

// Transmitter Vendor
if (MyForm.Manufacturers.value != "%"){
MyForm.SQL.value = MyForm.SQL.value + "VENDOR_CODE = " +
MyForm.Manufacturers.value + " And ";
lRetVal = true;
}

// Transmitter Model
if (MyForm.ShortModels.value != "%"){
MyForm.SQL.value = MyForm.SQL.value + "Substring(DEVICE_NAME,1,4) =
'" + MyForm.ShortModels.value + "' And ";
lRetVal = true;
}

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

// Span - Range
if (MyForm.RangeUnits.value != "%"){
MyForm.SQL.value = MyForm.SQL.value + "(RRANGELOWER >= " +
MyForm.LRange.value + " And " +
"RRANGEUPPER <= " + MyForm.URange.value + ") And ";

// Units
MyForm.SQL.value = MyForm.SQL.value + "UNIT_NAME = '" +
MyForm.RangeUnits.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:

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

grdInstList.DataSource = query;
grdInstList.DataBind();

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 4156
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<CalServicequery = 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.SelectedValue)

I would write as:

short vendorCode = Convert.ToInt16(ddlVendor.SelectedValue);
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...@gmail.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.SelectedValue)

I would write as:

short vendorCode = Convert.ToInt16(ddlVendor.SelectedValue);
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...@gmail.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.SelectedValue);
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
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...
2
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...
2
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...
6
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...
8
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 ,...
0
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...
0
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...
12
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...
10
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...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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,...

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.