如何:连接到数据库 (LINQ to SQL)
更新:November 2007
DataContext 是用来连接到数据库、从中检索对象以及将更改提交回数据库的主要渠道。使用 DataContext 时就像使用 ADO.NET SqlConnection 一样。事实上,DataContext 是用您提供的连接或连接字符串初始化的。有关更多信息,请参见 DataContext 方法(O/R 设计器)。
DataContext 的用途是将您对对象的请求转换成要对数据库执行的 SQL 查询,然后将查询结果汇编成对象。DataContext 通过实现与标准查询运算符(如 Where 和 Select)相同的运算符模式来实现 语言集成查询 (LINQ)。
![]() |
---|
维护安全连接最为重要。有关更多信息,请参见 LINQ to SQL 中的安全性。 |
示例
在下面的示例中,使用 DataContext 连接到 Northwind 示例数据库并检索所在城市为伦敦的客户行。
' 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 集合。
最佳的做法是声明一个强类型化的 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) { }
}
然后您就可以更加简单地将对来自伦敦的客户的查询表达成:
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);