LINQ to SQL动态查询举例分析

本篇内容介绍了“LINQ to SQL动态查询举例分析”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

LINQ to SQL动态查询

使用LINQ to SQL动态查询,这个例子用CreateQuery()方法创建一个IQueryable<T>类型表达式输出查询的语句。

这里给个例子说明一下:

var c1 = Expression.Parameter(typeof(Customer), "c");  PropertyInfo City = typeof(Customer).GetProperty("City");   var pred = Expression.Lambda<Func<Customer, bool>>(  Expression.Equal(  Expression.Property(c1, City),  Expression.Constant("Seattle")   ), c1  );  IQueryable custs = db.Customers;  Expression expr = Expression.Call(typeof(Queryable), "Where",  new Type[] { custs.ElementType }, custs.Expression, pred);  IQueryable<Customer> q = db.Customers.AsQueryable().  Provider.CreateQuery<Customer>(expr);

Log属性用于将SQL查询或命令打印到TextReader。此方法对了解 LINQ to SQL功能和调试特定的问题可能很有用。

下面的示例使用Log属性在SQL代码执行前在控制台窗口中显示此代码。我们可以将此属性与查询、插入、更新和删除命令一起使用。

//关闭日志功能  //db.Log = null;  //使用日志功能:日志输出到控制台窗口  db.Log = Console.Out;  var q = from c in db.Customers  where c.City == "London"  select c;  //日志输出到文件  StreamWriter sw = new StreamWriter(Server.MapPath("log.txt"), true);  db.Log = sw;  var q = from c in db.Customers  where c.City == "London"  select c;  sw.Close();

“LINQ to SQL动态查询举例分析”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!