天天躁日日躁狠狠躁AV麻豆-天天躁人人躁人人躁狂躁-天天澡夜夜澡人人澡-天天影视香色欲综合网-国产成人女人在线视频观看-国产成人女人视频在线观看

一步一步學Linq to sql(二):DataContext與實體

系列文章導航:

一步一步學Linq to sql(一):預備知識

一步一步學Linq to sql(二):DataContext與實體

一步一步學Linq to sql(三):增刪改

一步一步學Linq to sql(四):查詢句法

一步一步學Linq to sql(五):存儲過程

一步一步學Linq to sql(六):探究特性

一步一步學Linq to sql(七):并發與事務

一步一步學Linq to sql(八):繼承與關系

一步一步學Linq to sql(九):其它補充

一步一步學Linq to sql(十):分層構架的例子


DataContext

       DataContext類型(數據上下文)是System.Data.Linq命名空間下的重要類型,用于把查詢句法翻譯成SQL語句,以及把數據從數據庫返回給調用方和把實體的修改寫入數據庫。

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

l         以日志形式記錄DataContext生成的SQL

l         執行SQL(包括查詢和更新語句)

l         創建和刪除數據庫

DataContext是實體和數據庫之間的橋梁,那么首先我們需要定義映射到數據表的實體。

定義實體類

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數據庫為例,上述Customers類被映射成一個表,對應數據庫中的 Customers表。然后在類型中定義了三個屬性,對應表中的三個字段。其中,CustomerID字段是主鍵,如果沒有指定Column特性的Name屬性,那么系統會把屬性名作為數據表的字段名,也就是說實體類的屬性名就需要和數據表中的字段名一致。

       現在,創建一個ASP.NET頁面,然后在頁面上加入一個GridView控件,使用下面的代碼進行綁定數據:

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類型把實體類和數據庫中的數據進行關聯。你可以直接在DataContext的構造方法中定義連接字符串,也可以使用IDbConnection

using System.Data.SqlClient;

 

IDbConnection conn = new SqlConnection("server=xxx;database=Northwind;uid=xxx;pwd=xxx");

DataContext ctx = new DataContext(conn);

       之后,通過GetTable獲取表示底層數據表的Table類型,顯然,數據庫中的Customers表的實體是Customer類型。隨后的查詢句法,即使你不懂SQL應該也能看明白。從Customers表中找出CustomerID以“A”開頭的記錄,并把CustomersIDName以及City封裝成新的匿名類型進行返回。

       結果如下圖:

 

系列文章導航:

一步一步學Linq to sql(一):預備知識

一步一步學Linq to sql(二):DataContext與實體

一步一步學Linq to sql(三):增刪改

一步一步學Linq to sql(四):查詢句法

一步一步學Linq to sql(五):存儲過程

一步一步學Linq to sql(六):探究特性

一步一步學Linq to sql(七):并發與事務

一步一步學Linq to sql(八):繼承與關系

一步一步學Linq to sql(九):其它補充

一步一步學Linq to sql(十):分層構架的例子


強類型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方法獲取了修改后的實體,并輸出了修改內容。

 

系列文章導航:

一步一步學Linq to sql(一):預備知識

一步一步學Linq to sql(二):DataContext與實體

一步一步學Linq to sql(三):增刪改

一步一步學Linq to sql(四):查詢句法

一步一步學Linq to sql(五):存儲過程

一步一步學Linq to sql(六):探究特性

一步一步學Linq to sql(七):并發與事務

一步一步學Linq to sql(八):繼承與關系

一步一步學Linq to sql(九):其它補充

一步一步學Linq to sql(十):分層構架的例子


執行查詢

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();

       前一篇文章已經說了,雖然Linq to sql能實現90%以上的TSQL功能。但是不可否認,對于復雜的查詢,使用TSQL能獲得更好的效率。因此,DataContext類型也提供了執行SQL語句的能力。代碼的執行結果如下圖:

 

創建數據庫

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) { }

}

       這段代碼在數據庫中創建了名為testdb的數據庫,等同于下面的腳本:

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]

       同時,DataContext還提供了DeleteDatabase()方法,在這里就不列舉了。

 

使用DbDataReader數據源

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獲取數據,增加了靈活性的同時也增加了性能。

看到這里,你可能會覺得手工定義和數據庫中表對應的實體類很麻煩,不用擔心,VS2008提供了自動生成實體類以及關系的工具,工具的使用將在以后講解。今天就講到這里,和DataContext相關的事務、加載選項、并發選項以及關系實體等高級內容也將在以后講解。

it知識庫一步一步學Linq to sql(二):DataContext與實體,轉載需保留來源!

鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。

主站蜘蛛池模板: 午夜DV内射一区区 | 黑人玩弄极品人妻系列 | 精品午夜国产福利观看 | 麻豆E奶女教师国产精品 | 蜜柚影院在线观看免费高清中文 | 语文老师扒开胸罩喂我奶 | 第四色男人天堂 | 男女交性视频无遮挡全过程 | 99久久婷婷国产综合精品青草 | 亚洲精品久久国产高清 | 美美哒高清在线播放8 | 中文有码中文字幕免费视频 | 人人做人人干 | jzz大全18 | 人妖xxhdxx| 亚洲男人的天堂久久精品麻豆 | eussse手机电影在线观看 | 啦啦啦WWW在线观看免费高清版 | 亚洲高清在线视频 | 扒开老师大腿猛进AAA片 | 强壮的公次次弄得我高潮韩国电影 | 97在线国内自拍视频 | 达达兔午夜一级毛片 | 欧美视频 亚洲视频 | 亚洲欧美日韩精品自拍 | 嫩草影院在线观看网站成人 | 一个人高清在线观看日本免费 | 被黑人群jian又粗又大H | 免费韩国伦理2017最新 | 日韩人妻无码精品久久中文字幕 | 国产精品视频在线自在线 | 亚洲欧美国产综合在线 | 日日a.v拍夜夜添久久免费 | 男人脱女人衣服吃奶视频 | 国产精品久久久久精品A片软件 | 亚洲成人黄色片 | 精品免费久久久久久影院 | 99久久全国免费久久爱 | 日本人吃奶玩奶虐乳 | 99久久久国产精品免费调教 | 思思久久99热只有频精品66 |