一步一步学Linq to sql(二):DataContext与实体

简介: DataContext  DataContext类型(数据上下文)是System.Data.Linq命名空间下的重要类型,用于把查询句法翻译成SQL语句,以及把数据从数据库返回给调用方和把实体的修改写入数据库。

DataContext

 DataContext类型(数据上下文)是System.Data.Linq命名空间下的重要类型,用于把查询句法翻译成SQL语句,以及把数据从数据库返回给调用方和把实体的修改写入数据库。

       DataContext提供了以下一些使用的功能:

        以日志形式记录DataContext生成的SQL

        执行SQL(包括查询和更新语句)

        创建和删除数据库

DataContext是实体和数据库之间的桥梁,那么首先我们需要定义映射到数据表的实体。

 

定义实体类

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;

namespace DataContext
{
    [Table(Name = "Customers")]
    public class Customer
    {
        [Column(IsPrimaryKey = true)]
        public string CustomerID { get; set; }

        [Column(Name = "ContactName")]
        public string Name { get; set; }

        [Column]
        public string City { get; set; }
    }
}

  以Northwind数据库为例,上述Customers类被映射成一个表,对应数据库中的 Customers表。然后在类型中定义了三个属性,对应表中的三个字段。其中,CustomerID字段是主键,如果没有指定Column特性的Name属性,那么系统会把属性名作为数据表的字段名,也就是说实体类的属性名就需要和数据表中的字段名一致。

            ///DataContext
            DataContext ctx = new DataContext(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
            Table<Customer> Customers = ctx.GetTable<Customer>();
            var Cus=from c in Customers
                    where c.CustomerID.StartsWith("A")
                    select new {顾客ID=c.CustomerID, 顾客名=c.Name, 城市=c.City};
            foreach (var ct in Cus.ToList())
            {
                Console.WriteLine("姓名为:{0}在城市{1}",ct.顾客名,ct.城市);
            }

    使用DataContext类型把实体类和数据库中的数据进行关联。你可以直接在DataContext的构造方法中定义连接字符串,也可以使用IDbConnection

            IDbConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
            DataContext dc= new DataContext(conn);
            Customers = dc.GetTable<Customer>();

结果显示如下

 

强类型DataContext

namespace DataContextTest
{
    public partial class NorthWindDataContext: DataContext
    {
 
        public Table<Customer> Customers;
 
        public NorthWindDataContext(IDbConnection connection):base(connection) { }

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

    }
}

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

            ///强类型DataContext
            NorthWindDataContext NWDC = new NorthWindDataContext(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
            var NWCustomers = from NWs in NWDC.Customers
                              where NWs.CustomerID.StartsWith("A")
                              select new
                                  {
                                      顾客ID = NWs.CustomerID,
                                      顾客姓名 = NWs.Name,
                                      城市 = NWs.City
                                  };
            foreach (var cst in NWCustomers.ToList())
            {
                Console.WriteLine("姓名为:{0}在城市{1}", cst.顾客姓名, cst.城市);
            }

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

日志功能

            //日志功能
            NorthWindDataContext NWDC = new NorthWindDataContext(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
            StreamWriter sw = new StreamWriter("log.txt", true); // Append
            NWDC.Log = sw;
            var NWCustomers = from NWs in NWDC.Customers
                              where NWs.CustomerID.StartsWith("A")
                              select new
                                  {
                                      顾客ID = NWs.CustomerID,
                                      顾客姓名 = NWs.Name,
                                      城市 = NWs.City
                                  };
            foreach (var cst in NWCustomers.ToList())
            {
                Console.WriteLine("姓名为:{0}在城市{1}", cst.顾客姓名, cst.城市);
            }
            sw.Close();

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

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

探究查询

            ///探究查询
            NorthWindDataContext ctxc = new NorthWindDataContext(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
            var select = from cc in ctxc.Customers where cc.CustomerID.StartsWith("A") select new { 顾客ID = cc.CustomerID, 顾客名 = cc.Name, 城市 = cc.City };
            DbCommand cmd = ctxc.GetCommand(select);
            Console.WriteLine(cmd.CommandText);
            foreach (DbParameter parm in cmd.Parameters)
                Console.WriteLine(string.Format("参数名:{0},参数值:{1}", parm.ParameterName, parm.Value));
            Customer customer = ctxc.Customers.First();    ///修改第一条记录
            customer.Name = "aehyok";
            IList<object> queryText = ctxc.GetChangeSet().Updates;
            Console.WriteLine(((Customer)queryText[0]).Name);

  在这里,我们通过DataContextGetCommand方法获取了查询对应的DbCommand,并且输出了CommandText和所有的DbParameter。之后,我们又通过GetChangeSet方法获取了修改后的实体,并输出了修改内容。

执行查询

            ///执行查询
            NorthWindDataContext ctx = new NorthWindDataContext(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
            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%'");
            foreach (var ct in customers)
            {
                Console.WriteLine("姓名为:{0}在城市{1}", ct.Name, ct.City);
            }

  前一篇文章已经说了,虽然Linq to sql能实现90%以上的TSQL功能。但是不可否认,对于复杂的查询,使用TSQL能获得更好的效率。因此,DataContext类型也提供了执行SQL语句的能力。代码的执行结果如下图:

创建数据库

 

    [Table(Name = "test")]
    public class test
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true)]
        public int ID { get; set; }

        [Column(DbType = "varchar(20)")]
        public string Name { get; set; }
    }
    public partial class testContext : DataContext
    {
        public Table<test> test;
        public testContext(string connection) : base(connection) { }
    }
            ///创建数据库
            Console.WriteLine("创建数据库");
            testContext ctx = new testContext(ConfigurationManager.ConnectionStrings["ConnStringTest"].ConnectionString);
            ctx.CreateDatabase();

 段代码在数据库中创建了名为NorthwindTest的数据库,因为我在配置文件中创建的如下字符串连接

<add name="ConnStringTest" connectionString="server=.;database=NorthwindTest;uid=sa;pwd=saa"/>

 那么以及test数据库表也会一同被创建。同时,DataContext还提供了DeleteDatabase()方法,在这里就不列举了。

 

使用DbDataReader数据源

            ///使用DbDataReader数据源
            var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);

            var ctx = new DataContext(conn);

            var cmd = new SqlCommand("select * from customers where CustomerID like 'A%'", conn);

            conn.Open();

            var reader = cmd.ExecuteReader();
            var Recorders = ctx.Translate<Customer>(reader);
            foreach (var cus in Recorders)
            {
                Console.WriteLine("姓名为{0}城市为{1}",cus.Name,cus.City);
            }
            conn.Close();

 你同样可以选择使用DataReader获取数据,增加了灵活性的同时也增加了性

 

总结

  看到这里,你可能会觉得手工定义和数据库中表对应的实体类很麻烦,不用担心,VS提供了自动生成实体类以及关系的工具,工具的使用将在以后讲解。今天就讲到这里,和DataContext相关的事务、加载选项、并发选项以及关系实体等高级内容也将在以后讲解。

示例代码下载地址http://files.cnblogs.com/aehyok/DataContext.zip

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
目录
相关文章
|
2月前
|
SQL 开发框架 .NET
C# Linq SaveChanges()报错 You have an error in your SQL syntex
C# Linq SaveChanges()报错 You have an error in your SQL syntex
10 0
|
7月前
|
SQL 开发框架 .NET
SQL中in和not in在LINQ中的写法
SQL中in和not in在LINQ中的写法
|
8月前
|
SQL 开发框架 .NET
ef linq方式插入+sql操作数据注意事项
ef linq方式插入+sql操作数据注意事项
65 0
|
9月前
|
SQL 数据库
SQL Server--实体再复习
前些天小编所在的组织部重构,组长交给小编一项设计实体的活儿,它是我们软件灵魂(数据)的载体,实体的抽象影响到数据库设计,数据库设计的质量影响到整个程序的运营
|
SQL 存储 开发框架
Linq To SQl总结
Linq To SQl总结
149 0
Linq To SQl总结
|
SQL 开发框架 安全
Linq to SQL中的ColumnAttribute中的Expression
在Linq to SQL中,使用ColumnAttribute特性来关联数据库和实体类。这个Atrribute也有很多属性可以设置。其中让人比较迷糊的是Expression,也折磨了我好几天才弄明白(因为官方的例子给的也让人迷糊,基本运行都无法通过)。
487 0
Linq to SQL中的ColumnAttribute中的Expression
|
SQL .NET 开发框架
Linq SQL 动态个数where查询
Linq SQL 动态个数where查询,从parts表中查找工件类型ID为1、2或6...(个数不定)的所有part。
8403 0