HOW TO:連接到資料庫 (LINQ to SQL)
更新: November 2007
DataContext 是主要管道,您可以透過該管道連接至資料庫、擷取資料庫中的物件,以及將變更送回給資料庫。而 DataContext 的使用方式與 ADO.NET SqlConnection 的使用方式相同。事實上,DataContext 是使用您所提供的連接或連接字串 (Connection String) 來初始化。如需詳細資訊,請參閱 DataContext 方法 (O/R 設計工具)。
DataContext 的用途是將物件的要求轉譯為針對資料庫進行的 SQL 查詢,然後再從結果中組合物件。DataContext 會實作與標準查詢運算子 (如 Where 和 Select) 相同的運算子模式,來啟用 Language-Integrated Query (LINQ)。
安全性注意事項: |
---|
維護安全的連接是最重要的事。如需詳細資訊,請參閱 LINQ to SQL 的安全性。 |
範例
在下列範例中,DataContext 是用來連接至 Northwind 範例資料庫,以及擷取城市為倫敦 (London) 之客戶的資料列。
' DataContext takes a connection string.
Dim db As New DataContext("…\Northwnd.mdf")
' Get a typed table to run queries.
Dim Customers As Table(Of Customer) = db.GetTable(Of Customer)()
' Query for customer from London.
Dim Query = _
From cust In Customers _
Where cust.City = "London" _
Select cust
For Each cust In Query
Console.WriteLine("id=" & cust.CustomerID & _
", City=" & cust.City)
Next
// DataContext takes a connection string.
DataContext db = new DataContext(@"c:\Northwnd.mdf");
// Get a typed table to run queries.
Table<Customer> Customers = db.GetTable<Customer>();
// Query for customers from London.
var query =
from cust in Customers
where cust.City == "London"
select cust;
foreach (var cust in query)
Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);
使用實體類別來識別每個資料庫資料表,這樣每個資料庫資料表會以透過 GetTable 方法取得的 Table 集合表示。
最佳做法是宣告強型別 (Strongly Typed) DataContext,而不是依賴基本 DataContext 類別和 GetTable 方法。強型別 DataContext 會將所有 Table 集合宣告為內容的成員 (如下列範例所示)。
Partial Public Class Northwind
Inherits DataContext
Public Customers As Table(Of Customer)
Public Orders As Table(Of Order)
Public Sub New(ByVal connection As String)
MyBase.New(connection)
End Sub
End Class
public partial class Northwind : DataContext
{
public Table<Customer> Customers;
public Table<Order> Orders;
public Northwind(string connection) : base(connection) { }
}
接著,您可以用下列更簡單的方式表示針對倫敦 (London) 客戶的查詢:
Dim db As New Northwind("...\Northwnd.mdf")
Dim query = _
From cust In db.Customers _
Where cust.City = "London" _
Select cust
For Each cust In query
Console.WriteLine("id=" & cust.CustomerID & _
", City=" & cust.City)
Next
Northwnd db = new Northwnd(@"c:\Northwnd.mdf");
var query =
from cust in db.Customers
where cust.City == "London"
select cust;
foreach (var cust in query)
Console.WriteLine("id = {0}, City = {1}", cust.CustomerID,
cust.City);