using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.ComponentModel;
using System.Collections.Generic;
using System.IO;
using DAL;
/// <summary>
/// PagingAndLogging 的摘要说明
/// </summary>
[DataObject]
public class PagingAndLogging
{
[DataObjectMethod(DataObjectMethodType.Select, true)]
public List<Products> GetProduct( int startRowIndex, int maximumRows)
{
NorthwindDataContext ctx = new NorthwindDataContext();
// System.Data.Linq.DataContext的记录日志的功能
StreamWriter sw = new StreamWriter(HttpContext.Current.Request.PhysicalApplicationPath + "Log.txt", true);
ctx.Log = sw;
var products = (from p in ctx.Products
select p).Skip(startRowIndex).Take(maximumRows);
// products实现了IQueryable<T>接口
// 所以可以用如下方法从中获取DbCommand
System.Data.Common.DbCommand cmd = ctx.GetCommand(products);
string commandText = cmd.CommandText;
foreach (System.Data.Common.DbParameter param in cmd.Parameters)
{
string parameterName = param.ParameterName;
object value = param.Value;
}
// 延迟执行(Deferred Execution)
// products实现了IEnumerable<T>接口
// IEnumerable<T>接口的一个特性是,实现它的对象可以把实际的查询运算延迟到第一次对返回值进行迭代(yield)的时候
// ToList()之前,如果是LINQ to SQL的话,那么就可以通过products.ToString()查看LINQ生成的T-SQL
// ToList()后则执行运算
var listProducts = products.ToList();
// 执行运算后System.Data.Linq.DataContext会记录日志,所以应该在执行运算后Close掉StreamWriter
sw.Flush();
sw.Close();
return listProducts;
}
public int GetProductCount( int startRowIndex, int maximumRows)
{
NorthwindDataContext ctx = new NorthwindDataContext();
StreamWriter sw = new StreamWriter(HttpContext.Current.Request.PhysicalApplicationPath + "Log.txt", true);
ctx.Log = sw;
// Count查询操作符(不延迟) - 返回集合中的元素个数
int c = (from p in ctx.Products
select 0).Count();
sw.Flush();
sw.Close();
return c;
}
}