Where
Use the Where method to add further filtering criteria to a
SimpleQuery
. If criteria already exist, old and new criteria are combined
with the AND
operator.
Syntax
public SimpleQuery Where( SimpleExpression criteria )
Parameters
criteria
-
Type:
SimpleExpression
A (concatenated sequence of) search criteria. For example,dbo.Album.GenreId == 1
.
Return Value
Type: SimpleQuery
A SimpleQuery
object containing a Where clause.
Exceptions
Exception | Condition |
---|---|
FormatException - or - BadExpressionException |
criteria is a malformed SimpleExpression |
UnresolvableObjectException |
criteria has been assigned a SimpleExpression containing a field that does not exist |
ArgumentException |
criteria has been assigned zero or more than one SimpleExpression |
InvalidOperationException |
Where has been called without a base command - All , FindAllBy etc. |
Note that issues #321, and #322 are still open with regards to exceptions thrown by Where
.
Remarks
Using the Where
method allows you to add to the filtering criteria you may have already given your
Find*
, Add
and Get
queries. For example, the following commands all produce the same SQL.
db.Albums .FindAllByGenreId(1) .Select(db.Albums.Title) .Where(db.Albums.AlbumId > 400); db.Albums .FindAll(db.Albums.GenreId == 1 && db.Albums.AlbumId > 400) .Select(db.Albums.Title); db.Albums .All() .Select(db.Albums.Title) .Where(db.Albums.GenreId == 1 && db.Albums.AlbumId > 400);
Building Complex SimpleExpressions
Where
takes a single SimpleExpression
as a parameter.
If the command it is qualifying already has filtering criteria on it, the new criteria is appending to the old
using the AND
operator. For example, both these commands:
db.Albums .All() .Select(db.Albums.Title) .Where(db.Albums.GenreId == 1 || db.Albums.GenreId == 2) .Where(db.Albums.ArtistId == 120); db.Albums .FindAll(db.Albums.GenreId == 1 || db.Albums.GenreId == 2) .Select(db.Albums.Title) .Where(db.Albums.ArtistId == 120);
produce the following SQL. Note that parentheses are generated to maintain the correct interpretation of each filter criteria.
select [dbo].[Album].[Title] FROM [dbo].[Album] WHERE ( ([dbo].[Album].[GenreId] = @p1 OR [dbo].[Album].[GenreId] = @p2) AND [dbo].[Album].[ArtistId] = @p3) @p1 (Int32) = 1 @p2 (Int32) = 2 @p3 (Int32) = 120
If you wish to build up a set of filter criteria based on a set of business rules however, you may find it easier to build
up a SimpleExpression
separately and then add it to the command with a single call to Where rather than multiple calls. For example,
var expr1 = db.Albums.GenreId == 1; var expr2 = db.Albums.GenreId == 2; var expr3 = db.Albums.ArtistId == 120; return db.Albums.All().Where((expr1 || expr2) && expr3);
This approach has the added advantage that you can concatenate SimpleExpression
s with OR
as well as AND
.