0

How to get Total row Count & the records from the below query?

Contracts cont = db.contracts.SqlQuery("SELECT TOP (20) * 
  FROM (SELECT 
            ROW_NUMBER() OVER (ORDER BY dbo.Contracts.expDate desc) As RowID, 
            dbo.Contracts.*, 
            TotalRows=COUNT(*) OVER() 
        FROM dbo.Contracts  
        Where dbo.Contracts.cancelled = 1) as temp 
  WHERE temp.RowID >" + 20).ToList();

I'm getting the records but don't know how to get the Total row Count. Can Any body suggest best method to get the Total row Count & the records from the above query?

1 Answer 1

2

Your code won't work because you're returning a list of Contracts AND a count, but you're trying to assign it to only a Contracts. You need to project to an anonymous type, or create a custom type to project to that includes both the count and a collection of Contracts.

Why do you insist on using a sql query? This should do the same thing.

var contracts = (from x in db.contacts where x.cancelled == 1 
                 orderby x.expDate descending 
                 select new { Count=x.Count(), Records=x.Skip(20).Take(20) }).ToList();

Unless you want the total rows without the where clause, in which case it would be:

var contracts = (from x in db.contacts orderby x.expDate descending 
                 select new { Count=x.Count(), 
                   Records=x.Where(y => y.canceled == 1).Skip(20).Take(20) }).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

@user2254395 - "getting error" doesn't help. Since I don't have access to your actual source code, I can't know the real names of objects and their properties.. you will have to figure that out, because YOU have access to the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.