views:

72

answers:

2

I have a table of WorkOrders. The table has a PrimaryWorker & PrimaryPay field. It also has a SecondaryWorker & SecondaryPay field (which can be null).

I wish to run 2 very similar queries & union them so that it will return a Worker Field & Pay field. So if a single WorkOrder record had both the PrimaryWorker and SecondaryWorker field populated I would get 2 records back.

The "where clause" part of these 2 queries is very similar and long to construct. Here's a dummy example

var q = ctx.WorkOrder.Where(w => w.WorkDate >= StartDt && w.WorkDate <= EndDt);

if(showApprovedOnly)
{
   q = q.Where(w => w.IsApproved);
}
//...more filters applied

Now I also have a search flag called "hideZeroPay". If that's true I don't want to include the record if the worker was payed $0. But obviously for 1 query I need to compare the PrimaryPay field and in the other I need to compare the SecondaryPay field.

So I'm wondering how to do this.

Can I clone my base query "q" and make a primary & secondary worker query out of it and then union those 2 queries together?

I'd greatly appreciate an example of how to correctly handle this.

Thanks very much for any help.

A: 

When you do your second Where you are actually cloning your query.

Here you create your initial queryable object.

var q = ctx.WorkOrder.Where(w => w.WorkDate >= StartDt && w.WorkDate <= EndDt);

Here you create a new queryable with the where associated

if(showApprovedOnly)
{
   q = q.Where(w => w.IsApproved);
}
//...more filters applied

All you need to do is create a new variable to store the ammended query.

var qw = q.Where(w=> w.IsApproved);

This works because the queryable is created as an object and the query itself is only run once you enumerate it.

Jonathan Park
A: 
DHN
After thinking about it, I've to say that your thoughts came up too. The reason is the ObjectQuery object. Well when I was writing my answer I just was guessing but now I know that it works.I don't know if a .Union() is executed on the database. But I'm interested on your results, after you have tried it. ;o)
DHN
Yeah, it does seem you get a new ObjectQuery back each time because query1.equals(query2) returns false.I noticed that I had to perform my projection ( Select() ) on each query before calling Union() for it to work properly.I then ran a ToTraceString() on the ObjectQuery and it does all apear to run on the DB.