Linq使用sqlmetal剖析
在向大家詳細(xì)介紹Linq使用sqlmetal之前,首先讓大家了解下外部映射文件,然后全面介紹Linq使用sqlmetal。
外部映射文件
我們可以Linq使用sqlmetal命令行工具來生成外部映射文件,使用方法如下:
1、開始菜單 -》 VS2008 -》VS工具 -》VS2008命令行提示
2、輸入命令:
- D:\Program Files\Microsoft Visual Studio 9.0\VC>sqlmetal /conn:server=xxx;
- database=Northwind;uid=xxx;pwd=xxx /map:c:\northwind.map /code:c:\northwind.cs
3、這樣,我們就可以在C盤下得到一個xml映射文件和C#的實體類代碼
4、把.cs文件添加到項目中來(放到App_Code目錄),然后使用下面的代碼加載映射文件:
- String path = @"C:\Northwind.map";
- XmlMappingSource xms = XmlMappingSource.FromXml(File.ReadAllText(path));
- Northwind ctx = new Northwind
("server=xxx;database=Northwind;uid=xxx;pwd=xxx", xms);
5、現(xiàn)在就可以照常進(jìn)行其它工作了。Linq使用sqlmetal可以很方便的同步數(shù)據(jù)庫與實體和映射文件。每次修改數(shù)據(jù)庫結(jié)構(gòu),從dbml設(shè)計器上刪除表、存儲過程然后再重新添加也是很麻煩的事情。
處理空值
- var count = (from c in ctx.Customers where c.Region == null select c).Count();
- Response.Write(count + "<br/>");
- var query = from emp in ctx.Employees select emp.ReportsTo;
- foreach (Nullable<int> r in query)
- {
- Response.Write(r.HasValue ? r.Value.ToString() + "<br/>" : "沒有<br/>");
- }
代碼執(zhí)行后捕獲到下面的SQL被執(zhí)行:
- SELECT COUNT(*) AS [value]
- FROM [dbo].[Customers] AS [t0]
- WHERE [t0].[Region] IS NULL
- SELECT [t0].[ReportsTo]
- FROM [dbo].[Employees] AS [t0]
【編輯推薦】