zoukankan      html  css  js  c++  java
  • Linq to sql(二):DataContext与实体(二)

    强类型DataContext

    public partial class NorthwindDataContext : DataContext

    {

        public Table<Customer> Customers;

        public NorthwindDataContext(IDbConnection connection) : base(connection) { }

        public NorthwindDataContext(string connection) : base(connection) { }

    }

           强类型数据上下文使代码更简洁:

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

    GridView1.DataSource = from c in ctx.Customers where c.CustomerID.StartsWith("A") select new { 顾客ID = c.CustomerID, 顾客名 = c.Name, 城市 = c.City };

    GridView1.DataBind();

           DataContext其实封装了很多实用的功能,下面一一介绍。

    日志功能

    using System.IO;

     

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

    StreamWriter sw = new StreamWriter(Server.MapPath("log.txt"), true); // Append

    ctx.Log = sw;

    GridView1.DataSource = from c in ctx.Customers where c.CustomerID.StartsWith("A") select new { 顾客ID = c.CustomerID, 顾客名 = c.Name, 城市 = c.City };

    GridView1.DataBind();

    sw.Close();

           运行程序后在网站所在目录生成了log.txt,每次查询都会把诸如下面的日志追加到文本文件中:

    SELECT [t0].[CustomerID], [t0].[ContactName], [t0].[City]

    FROM [Customers] AS [t0]

    WHERE [t0].[CustomerID] LIKE @p0

    -- @p0: Input String (Size = 2; Prec = 0; Scale = 0) [A%]

    -- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.20706.1

           应该说这样的日志对于调试程序是非常有帮助的。

    探究查询

    using System.Data.Common;

    using System.Collections.Generic;

     

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

    var select = from c in ctx.Customers where c.CustomerID.StartsWith("A") select new { 顾客ID = c.CustomerID, 顾客名 = c.Name, 城市 = c.City };

    DbCommand cmd = ctx.GetCommand(select);

    Response.Write(cmd.CommandText + "<br/>");

    foreach (DbParameter parm in cmd.Parameters)

        Response.Write(string.Format("参数名:{0},参数值:{1}<br/>", parm.ParameterName, parm.Value));

    Customer customer = ctx.Customers.First();

    customer.Name = "zhuye";

    IList<object> queryText = ctx.GetChangeSet().ModifiedEntities;

    Response.Write(((Customer)queryText[0]).Name);

           在这里,我们通过DataContextGetCommand方法获取了查询对应的DbCommand

    并且输出了CommandText和所有的DbParameter。之后,我们又通过GetChangeSet方法获取了修改后的实体,

    并输出了修改内容。

  • 相关阅读:
    XML文件的操作说明
    IIS中如何应用程序启用https协议
    sql server中的数据类型转换函数
    sql语句中的join连接(左连接、右连接、全连接、内连接)
    sql语句中日期相减的操作
    C# NameValueCollection集合
    json的两种表示结构(对象和数组).。
    ASP.NET中一般处理程序报的错误:由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值
    C#中类的实例是不能 获取到类中的静态方法和静态变量(Static)的,及原因
    《好好学Java 从零基础到项目实战》姗姗而来
  • 原文地址:https://www.cnblogs.com/kevin2013/p/1749107.html
Copyright © 2011-2022 走看看