在 SQL Server Compact 中使用 LINQ to SQL
如何使用 LINQ 等新的开发技术访问 SQL Server Compact 数据库(.sdf 文件)中的数据
在本文中,我将介绍如何使用 LINQ 等新的开发技术访问 SQL Server Compact 数据库(.sdf 文件)。LINQ 是微软发起的一项新倡议,旨在支持对象关系映射的概念和设计模式。LINQ 提供完全的类型安全性和编译时查询表达式检查,以最大限度地减少对象关系概念的不匹配,并能够将关系数据作为对象进行管理,从而为您的应用程序提供一种简便的方式来集成数据验证和业务逻辑规则。
开始解决方案
第一步是打开 Visual Studio.NET 2008,并创建一个控制台项目(见图 1)。
图 1
然后,转到 SQL Server Compact Edition 的安装目录 $PROGRAMFILES$\Microsoft SQL Compact Edition\v3.5\Samples,并将 Northwind.sdf 文件复制到解决方案目录中。让我们打开一个命令窗口控制台并切换到解决方案目录。
让我们在 Program Files\Microsoft SDKs\Windows\v6.0A\Bin\ 目录中调用 SQLMetal.exe 命令,以便为 .NET 框架的 LINQ to SQL 组件生成代码和映射(见图 2)。
图 2
现在,让我们将 Northwind.cs 文件添加到解决方案中,并添加对 System.Data.Linq.dll 程序集的引用(见图 3)。
图 3
最后,示例代码如列表 1 所示。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQ_SQLCompact
{
class Program
{
static void Main(string[] args)
{
string strConnString = "Northwind.sdf";
Northwind dbNorthwind = new Northwind(strConnString);
var query = from c in dbNorthwind.Customers
where c.City == "Paris"
select c;
foreach (Customers c in query)
{
System.Console.WriteLine("ContactName={0},
Address={1}, City={2}",c.ContactName, c.Address, c.City);
}
System.Console.WriteLine("Press any key to finish ...");
System.Console.Read();
}
}
}