通过使用 LINQ to SQL,可以使用 LINQ 技术访问 SQL 数据库,就像访问内存中集合一样。
例如,在下面的代码中,创建了 nw
对象来表示 Northwind
数据库,将 Customers
表作为目标,筛选出了来自 Customers
的 London
行,并选择了一个表示 CompanyName
的字符串以进行检索。
执行循环时,将检索到 CompanyName
值的集合。
// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(@"northwnd.mdf");
// or, if you are not using SQL Server Express
// Northwnd nw = new Northwnd("Database=Northwind;Server=server_name;Integrated Security=SSPI");
var companyNameQuery =
from cust in nw.Customers
where cust.City == "London"
select cust.CompanyName;
foreach (var customer in companyNameQuery)
{
Console.WriteLine(customer);
}
' Northwnd inherits from System.Data.Linq.DataContext.
Dim nw As New Northwnd("c:\northwnd.mdf")
' or, if you are not using SQL Server Express
' Dim nw As New Northwnd("Database=Northwind;Server=dschwart7;Integrated Security=SSPI")
Dim companyNameQuery = _
From cust In nw.Customers _
Where cust.City = "London" _
Select cust.CompanyName
For Each customer In companyNameQuery
Console.WriteLine(customer)
Next
后续步骤
有关一些其他示例,包括插入和更新,请参阅 使用 LINQ to SQL 可以执行的操作。
接下来,请尝试一些演练和教程,体验使用 LINQ to SQL。 请参阅通过演练学习。
最后,阅读 使用 LINQ to SQL 的典型步骤,了解如何开始自己的 LINQ to SQL 项目。