C# Linq 分页查询模板

1. SQL

 private static string GetAllStocksSql(string branch, string itemNo, string locationName, string lotControl, bool blnAvail, bool blnCount)
        {
            StringBuilder sql = new StringBuilder();

            if (blnCount)
            {
                sql.Append(" SELECT  Count(*) ");
            }
            else
            {
                sql.Append(@"
                            SELECT  ROW_NUMBER() OVER(ORDER BY s.ReceivingTime  ) AS Seq,
                                s.Id ,s.Branch ,s.PDLITM ItemNo ,f.IMDSC1 + f.IMDSC2 [Description] , f.IMUOM1 UM ,  
                                l.Location LocationName ,  s.Qty Quantity ,  s.ReceivingTime ReceivingDate ,  s.LotControl LotControl   ");
            }
            sql.Append(@"   FROM    Stock s
                                LEFT JOIN Location l ON s.Location = l.Id
                                LEFT JOIN F4101 f ON s.PDLITM = f.IMLITM");

            sql.AppendFormat(@" where s.Branch like '%{0}%'  and s.PDLITM like '%{1}%' 
                                and l.Location like '%{2}%' ", branch, itemNo, locationName);
            if (!string.IsNullOrEmpty(lotControl))
            {
                sql.Append(" and s.LotControl like '%" + lotControl + "%'");
            }
            if (blnAvail)
            {
                sql.Append(" and s.Qty >0");//只显示可用库存            
            }
            return sql.ToString();

        }

2. 查询

  public static IList GetAllStocks(string branch, string itemNo, string locationName, string lotControl,bool blnAvail, int startIndex, int endIndex)
        {
            string detailSql = GetAllStocksSql(branch, itemNo, locationName, lotControl,blnAvail, false);

            string sql = @"
            SELECT * FROM 
            (
                {2}
             ) AS TB WHERE Seq>={0} AND Seq<=({1})
            "; 
            sql = string.Format(sql, startIndex, endIndex, detailSql);

            return  WmsDataContext.Instance.ExecuteQuery<StocksTemp>(sql).ToList();
            
        }

3. 总量

public static int GetStocksCount(string branch, string itemNo, string locationName, string lotControl, bool blnAvail)
        {
            
            string sql = GetAllStocksSql(branch, itemNo, locationName, lotControl, blnAvail,true);
            return WmsDataContext.Instance.ExecuteQuery<int>(sql).FirstOrDefault();
        }
原文地址:https://www.cnblogs.com/machaofast/p/3145505.html