DataContext.ExecuteQuery的两种方法调用

ExecuteQuery主要用于DataContext类直接执行SQL语句的查询,在MSDN上有两种执行方法,下面为两种方法的不同调用:

1、ExecuteQuery<TResult>(String, Object[])   应该是微软的推荐方法,网上几乎都在用的方法

NorthwindDataContext ctx = new NorthwindDataContext("server=xxx;database=Northwind;uid=xxx;pwd=xxx");

string newcity = "Shanghai";

ctx.ExecuteCommand("update Customers set City={0} where CustomerID like 'A%'", newcity);

IEnumerable<Customer> customers = ctx.ExecuteQuery<Customer>("select * from Customers where CustomerID like 'A%'");

GridView1.DataSource = customers;

GridView1.DataBind();

2、ExecuteQuery(Type, String, Object[])  Type为要返回的 IEnumerable<T> 的类型。

DataContext db = new DataContext("Data Source=*******;Initial Catalog=*****;Persist Security Info=True;User ID=sa;Password=*****");
            StreamWriter sw = new StreamWriter(Server.MapPath("log.txt"), true);
            //db.Log = sw;
            Table<NewsList> news = db.GetTable<NewsList>();
            var select = from p in news select new { 标题 = p.title };
            IDbCommand cmd = db.GetCommand(select);
            var newss = db.ExecuteQuery(typeof(NewsList), "SELECT NewsID,TITLE FROM lmh_Newslist");
            foreach (var s in newss)
            {
                NewsList s1 = (NewsList)s;
                //Response.Write(s1.title);
            }
原文地址:https://www.cnblogs.com/superfeeling/p/4384768.html