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 ICommand Where( SimpleExpression criteria )
Parameters
criteria-
Type:
SimpleExpression
A (concatenated sequence of) search criteria. For example,dbo.Album.GenreId == 1.
Return Value
Type: ICommand
An object representation of the data retrieval query to be sent to a data store
Exceptions
| Exception | Condition |
|---|---|
RuntimeBinderException |
Where called without a query command to qualify |
System.Reflection.TargetParameterCountException |
Zero or more than one SimpleExpressions have been supplied to Where as parameters |
FormatException- or - RuntimeBinderException- or - Simple.Data.UnresolvableObjectException
|
Malformed SimpleExpression supplied to Where as parameter
|
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);
You must call Where with a single valid SimpleExpression
as a parameter else an Exception will be thrown.
You can find examples of setting common search conditions as SimpleExpressions here
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 SimpleExpressions with OR as well as AND.