|
系列文章導(dǎo)航:
一步一步學(xué)Linq to sql(一):預(yù)備知識
一步一步學(xué)Linq to sql(二):DataContext與實(shí)體
一步一步學(xué)Linq to sql(七):并發(fā)與事務(wù)
一步一步學(xué)Linq to sql(八):繼承與關(guān)系
一步一步學(xué)Linq to sql(九):其它補(bǔ)充
一步一步學(xué)Linq to sql(十):分層構(gòu)架的例子
DataContext
DataContext類型(數(shù)據(jù)上下文)是System.Data.Linq命名空間下的重要類型,用于把查詢句法翻譯成SQL語句,以及把數(shù)據(jù)從數(shù)據(jù)庫返回給調(diào)用方和把實(shí)體的修改寫入數(shù)據(jù)庫。
DataContext提供了以下一些使用的功能:
l 以日志形式記錄DataContext生成的SQL
l 執(zhí)行SQL(包括查詢和更新語句)
l 創(chuàng)建和刪除數(shù)據(jù)庫
DataContext是實(shí)體和數(shù)據(jù)庫之間的橋梁,那么首先我們需要定義映射到數(shù)據(jù)表的實(shí)體。
定義實(shí)體類
using System.Data.Linq.Mapping;
[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數(shù)據(jù)庫為例,上述Customers類被映射成一個(gè)表,對應(yīng)數(shù)據(jù)庫中的 Customers表。然后在類型中定義了三個(gè)屬性,對應(yīng)表中的三個(gè)字段。其中,CustomerID字段是主鍵,如果沒有指定Column特性的Name屬性,那么系統(tǒng)會把屬性名作為數(shù)據(jù)表的字段名,也就是說實(shí)體類的屬性名就需要和數(shù)據(jù)表中的字段名一致。
現(xiàn)在,創(chuàng)建一個(gè)ASP.NET頁面,然后在頁面上加入一個(gè)GridView控件,使用下面的代碼進(jìn)行綁定數(shù)據(jù):
using System.Data.Linq;
DataContext ctx = new DataContext("server=xxx;database=Northwind;uid=xxx;pwd=xxx"); Table<Customer> Customers = ctx.GetTable<Customer>(); GridView1.DataSource = from c in Customers where c.CustomerID.StartsWith("A") select new {顧客ID=c.CustomerID, 顧客名=c.Name, 城市=c.City}; GridView1.DataBind(); |
使用DataContext類型把實(shí)體類和數(shù)據(jù)庫中的數(shù)據(jù)進(jìn)行關(guān)聯(lián)。你可以直接在DataContext的構(gòu)造方法中定義連接字符串,也可以使用IDbConnection:
using System.Data.SqlClient;
IDbConnection conn = new SqlConnection("server=xxx;database=Northwind;uid=xxx;pwd=xxx"); DataContext ctx = new DataContext(conn); |
之后,通過GetTable獲取表示底層數(shù)據(jù)表的Table類型,顯然,數(shù)據(jù)庫中的Customers表的實(shí)體是Customer類型。隨后的查詢句法,即使你不懂SQL應(yīng)該也能看明白。從Customers表中找出CustomerID以“A”開頭的記錄,并把CustomersID、Name以及City封裝成新的匿名類型進(jìn)行返回。
結(jié)果如下圖:
系列文章導(dǎo)航:
一步一步學(xué)Linq to sql(一):預(yù)備知識
一步一步學(xué)Linq to sql(二):DataContext與實(shí)體
一步一步學(xué)Linq to sql(七):并發(fā)與事務(wù)
一步一步學(xué)Linq to sql(八):繼承與關(guān)系
一步一步學(xué)Linq to sql(九):其它補(bǔ)充
一步一步學(xué)Linq to sql(十):分層構(gòu)架的例子
強(qiáng)類型DataContext
public partial class NorthwindDataContext : DataContext { public Table<Customer> Customers; public NorthwindDataContext(IDbConnection connection) : base(connection) { } public NorthwindDataContext(string connection) : base(connection) { } } |
強(qiáng)類型數(shù)據(jù)上下文使代碼更簡潔:
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其實(shí)封裝了很多實(shí)用的功能,下面一一介紹。
日志功能
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(); |
運(yùn)行程序后在網(wǎng)站所在目錄生成了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 |
應(yīng)該說這樣的日志對于調(diào)試程序是非常有幫助的。
探究查詢
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("參數(shù)名:{0},參數(shù)值:{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); |
在這里,我們通過DataContext的GetCommand方法獲取了查詢對應(yīng)的DbCommand,并且輸出了CommandText和所有的DbParameter。之后,我們又通過GetChangeSet方法獲取了修改后的實(shí)體,并輸出了修改內(nèi)容。
系列文章導(dǎo)航:
一步一步學(xué)Linq to sql(一):預(yù)備知識
一步一步學(xué)Linq to sql(二):DataContext與實(shí)體
一步一步學(xué)Linq to sql(七):并發(fā)與事務(wù)
一步一步學(xué)Linq to sql(八):繼承與關(guān)系
一步一步學(xué)Linq to sql(九):其它補(bǔ)充
一步一步學(xué)Linq to sql(十):分層構(gòu)架的例子
執(zhí)行查詢
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(); |
前一篇文章已經(jīng)說了,雖然Linq to sql能實(shí)現(xiàn)90%以上的TSQL功能。但是不可否認(rèn),對于復(fù)雜的查詢,使用TSQL能獲得更好的效率。因此,DataContext類型也提供了執(zhí)行SQL語句的能力。代碼的執(zhí)行結(jié)果如下圖:
創(chuàng)建數(shù)據(jù)庫
testContext ctx = new testContext("server=xxx;database=testdb;uid=xxx;pwd=xxx"); ctx.CreateDatabase();
[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) { } } |
這段代碼在數(shù)據(jù)庫中創(chuàng)建了名為testdb的數(shù)據(jù)庫,等同于下面的腳本:
CREATE TABLE [dbo].[test]( [ID] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL, CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] |
同時(shí),DataContext還提供了DeleteDatabase()方法,在這里就不列舉了。
使用DbDataReader數(shù)據(jù)源
using System.Data.SqlClient;
var conn = new SqlConnection("server=xxx;database=Northwind;uid=xxx;pwd=xxx"); var ctx = new DataContext(conn); var cmd = new SqlCommand("select * from customers where CustomerID like 'A%'", conn); conn.Open(); var reader = cmd.ExecuteReader(); GridView1.DataSource = ctx.Translate<Customer>(reader); GridView1.DataBind(); conn.Close(); |
你同樣可以選擇使用DataReader獲取數(shù)據(jù),增加了靈活性的同時(shí)也增加了性能。
看到這里,你可能會覺得手工定義和數(shù)據(jù)庫中表對應(yīng)的實(shí)體類很麻煩,不用擔(dān)心,VS2008提供了自動生成實(shí)體類以及關(guān)系的工具,工具的使用將在以后講解。今天就講到這里,和DataContext相關(guān)的事務(wù)、加載選項(xiàng)、并發(fā)選項(xiàng)以及關(guān)系實(shí)體等高級內(nèi)容也將在以后講解。
it知識庫:一步一步學(xué)Linq to sql(二):DataContext與實(shí)體,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時(shí)間聯(lián)系我們修改或刪除,多謝。