简体   繁体   中英

Entity FrameWork SQL Query

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM