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封裝成新的匿名型別進行返回。
結果如下圖: