Nested or where queries with QuerySpec

Posts   
 
    
dconlisk
User
Posts: 2
Joined: 26-Jan-2012
# Posted on: 04-Apr-2012 09:56:35   

Hi all,

I'm trying to generate a query of the general form WHERE A AND B AND (C OR D OR E)

How can I achieve this? I tried this below but it's not quite correct - it's of the form WHERE A AND B OR C OR D OR E

var qf = new QueryFactory(); var q = qf.Job; q = q.Where(JobFields.JobTitle.Like('%' + criteria.Title + '%')); // Condition A q = q.Where(JobFields.JobLocation.Like('%' + criteria.Location + '%')); // Condition B q = q.OrWhere(JobFields.LokIdSector == 13); // Condition C q = q.OrWhere(JobFields.LokIdSector == 14); // Condition D q = q.OrWhere(JobFields.LokIdSector == 15); // Condition E

(where criteria is an object containing strings for Title and Location).

Any help much appreciated!

Thanks,

David

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 04-Apr-2012 11:39:53   

Example:

SELECT * FROM Customers WHERE Country = 'UK' AND (City = 'Cowes' OR ContactTitle = 'Sales Agent')

var q = qf.Customer
    .Where(CustomerFields.Country == "UK")
    .AndWhere(new PredicateExpression(CustomerFields.City == "Cowes" | CustomerFields.ContactTitle == "Sales Agent"));
Otis avatar
Otis
LLBLGen Pro Team
Posts: 39910
Joined: 17-Aug-2003
# Posted on: 04-Apr-2012 12:11:38   

QuerySpec offers nice extension methods for predicateexpression construction wink ->

var q = qf.Customer
            .Where(CustomerFields.Country == "UK")
            .AndWhere((CustomerFields.City == "Cowes").Or(CustomerFields.ContactTitle == "Sales Agent"));

so it has a quite natural flow.

Frans Bouma | Lead developer LLBLGen Pro
dconlisk
User
Posts: 2
Joined: 26-Jan-2012
# Posted on: 04-Apr-2012 15:09:39   

Excellent - thanks to you both!

For anyone else reading, here's how I accomplished the nested OR statement in a loop using a PredicateExpression object:

                var qf = new QueryFactory();
                var q = qf.Job;
                q = q.Where(JobFields.JobTitle.Like('%' + criteria.Title + '%'));
                q = q.Where(JobFields.JobLocation.Like('%' + criteria.Location + '%'));

                PredicateExpression p = new PredicateExpression();

                // Add an or where clause for each sector id specified in the search criteria
                foreach (int sectorId in criteria.Sectors)
                {
                    p.AddWithOr(JobFields.LokIdSector == sectorId);

                }
                q = q.AndWhere(p);

                return (EntityCollection<JobEntity>)adapter.FetchQuery(q);

Thanks again!

David