markrendle / Simple.Data

A light-weight, dynamic data access component for C# 4.0
MIT License
1.33k stars 303 forks source link

Get Total Count After Where Has Been Applied? #364

Closed parkerhillius closed 9 years ago

parkerhillius commented 9 years ago

I'm looking for a way to get the total count (for paging) after where clauses may or may not have been applied.

var query = _db.Table.All() .Where(_db.Table.Column >= startDateTime && _db.Table.Column < endDateTime); if (userId.HasValue) { query = query.Where(_db.Table.UserId == userId.Value); }

I've tried the following: int totalCount = 0; query = query.WithTotalCount(out totalCount);

With error: Cannot invoke a non-delegate type

I've also tried the following: int totalCount = query.GetCount();

With the same error.

Is there anyway to do what I'm looking for? Thank you.

pettys commented 9 years ago

Hey Parker -- did you find the answer to this? I had the same question and wondering why you closed it. :)

parkerhillius commented 9 years ago

Hi Jason - I implemented like so:

var expr = GetExpression(startDateTime, endDateTime, userId); var totalCount = _db.Table.GetCount(expr); var records = _db.Table.All().Where(expr) .OrderBy(...) .Skip(x) .Take(y);

private dynamic GetExpression(DateTime startDateTime, DateTime endDateTime, Guid? userId) { var expr = _db.Table.Column >= startDateTime && _db.Table.Column < endDateTime; if (userId.HasValue) { expr = expr && _db.Table.UserId == userId.Value; } return expr; }

pettys commented 9 years ago

Ah, thanks -- that's a very tidy approach!