日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

一步一步学linq to sql(二)

發布時間:2023/12/20 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 一步一步学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”開頭的記錄,并把CustomersID、Name以及City封裝成新的匿名類型進行返回。

?????? 結果如下圖:

強類型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);

?????? 在這里,我們通過DataContext的GetCommand方法獲取了查詢對應的DbCommand,并且輸出了CommandText和所有的DbParameter。之后,我們又通過GetChangeSet方法獲取了修改后的實體,并輸出了修改內容。

執行查詢

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相關的事務、加載選項、并發選項以及關系實體等高級內容也將在以后講解。



轉載于:https://www.cnblogs.com/kingdom_0/articles/2043528.html

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的一步一步学linq to sql(二)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。