日期:2014-05-20 浏览次数:20660 次
//依据IQueryable数据源构造一个查询
IQueryable<City> custs = db.DataBase.Citys;
//组建一个表达式树来创建一个参数
ParameterExpression param =
Expression.Parameter(typeof(City), "c");
//组建表达式树:c.ContactName
Expression selector = Expression.Property(param,
typeof(City).GetProperty("Name"));
Expression pred = Expression.Lambda(selector, param);
//组建表达式树:Select(c=>c.ContactName)
Expression expr = Expression.Call(typeof(Queryable), "Select",
new Type[] { typeof(City), typeof(string) },
Expression.Constant(custs), pred);
//使用表达式树来生成动态查询
IQueryable<string> query = db.DataBase.Citys.AsQueryable()
.Provider.CreateQuery<string>(expr);
//使用GetCommand方法获取SQL语句
//System.Data.Common.DbCommand cmd = db.GetCommand(query);
var result = query.ToList();