Select Active and Recently Completed "Tasks" from Table
I have a Tasks table something like;
PK TaskId
TaskName
Notes
...
...
FK StatusId
DateCompleted
What I want to do is get a list if tasks that are active plus any tasks completed in the last 7 days.
At th开发者_如何学Ce moment I have;
var then = DateTime.Today.AddDays(-7);
return _db.Tasks
.Where(t => (t.StatusId != 1))
.Union(_db.Tasks
.Where(t => (t.DateCompleted >= then))
);
Is this the most sensible way to do it? I am creating the DB from scratch so that can change to suit a better method :)
Cheers Si
The other alternative is:
var day = DateTime.Today.AddDays(-7);
return _db.Tasks
.Where(t => t.StatusId != 1 || t.DateCompleted >= day);
This is more concise but can only use a single index (either StatusId or DateCompleted). Your Union
technique might allow using both indices but has a chance of overlapping.
To improve your solution you can use Concat()
instead of Union()
which does not eliminate duplicates, if you're sure there won't be an overlap between two sets. Concat()
will turn into UNION ALL
which is faster than UNION
.
The database itself seems OK, but couldn't you just use a simple "or" in the query?
_db.Tasks.Where(t => t.StatusId != -1 || t.DateCompleted >= then)
精彩评论