Linq使用sqlmetal剖析

在向大家详细介绍Linq使用sqlmetal之前,首先让大家了解下外部映射文件,然后全面介绍Linq使用sqlmetal。

外部映射文件

我们可以Linq使用sqlmetal命令行工具来生成外部映射文件,使用方法如下:
1、开始菜单 -》 VS2008 -》VS工具 -》VS2008命令行提示

2、输入命令:

  1. D:\Program Files\Microsoft Visual Studio 9.0\VC>sqlmetal /conn:server=xxx;
  2. database=Northwind;uid=xxx;pwd=xxx /map:c:\northwind.map /code:c:\northwind.cs

3、这样,我们就可以在C盘下得到一个xml映射文件和C#的实体类代码

4、把.cs文件添加到项目中来(放到App_Code目录),然后使用下面的代码加载映射文件:

  1. String path = @"C:\Northwind.map";
  2. XmlMappingSource xms = XmlMappingSource.FromXml(File.ReadAllText(path));
  3. Northwind ctx = new Northwind
    ("server=xxx;database=Northwind;uid=xxx;pwd=xxx", xms);

5、现在就可以照常进行其它工作了。Linq使用sqlmetal可以很方便的同步数据库与实体和映射文件。每次修改数据库结构,从dbml设计器上删除表、存储过程然后再重新添加也是很麻烦的事情。

处理空值

  1. var count = (from c in ctx.Customers where c.Region == null select c).Count();
  2. Response.Write(count + "<br/>");
  3. var query = from emp in ctx.Employees select emp.ReportsTo;
  4. foreach (Nullable<int> r in query)
  5. {
  6. Response.Write(r.HasValue ? r.Value.ToString() + "<br/>" : "没有<br/>");
  7. }

代码执行后捕获到下面的SQL被执行:

    1. SELECT COUNT(*) AS [value]
    2. FROM [dbo].[Customers] AS [t0]
    3. WHERE [t0].[Region] IS NULL
    4. SELECT [t0].[ReportsTo]
    5. FROM [dbo].[Employees] AS [t0]
posted @ 2012-05-31 18:58  Peter.Luo  阅读(155)  评论(0)    收藏  举报