外部映射文件
我們可以使用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、現在就可以照常進行其它工作了。使用sqlmetal可以很方便的同步數據庫與實體和映射文件。每次修改數據庫結構,從dbml設計器上刪除表、存儲過程然後再重新添加也是很麻煩的事情。
處理空值
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/>");
}
代碼執行後捕獲到下面的SQL被執行:
SELECT COUNT(*) AS [value]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[Region] IS NULL
SELECT [t0].[ReportsTo]
FROM [dbo].[Employees] AS [t0]
已編譯查詢
對於一些在項目中經常被用到的查詢可以封裝成已編譯查詢,這樣就能提高執行效率:
static class Queries
{
public static Func<NorthwindDataContext, string, IQueryable<Customer>>
CustomersByCity = CompiledQuery.Compile((NorthwindDataContext ctx, string city) => from c in ctx.Customers where c.City == city select c);
}
調用查詢方式如下:
GridView1.DataSource = Queries.CustomersByCity(ctx, "London");
GridView1.DataBind();
獲取一些信息
var query = from c in ctx.Customers select c;
Response.Write("Provider類型:" + ctx.Mapping.ProviderType + "<br/>");
Response.Write("數據庫:" + ctx.Mapping.DatabaseName + "<br/>");
Response.Write("表:" + ctx.Mapping.GetTable(typeof(Customer)).TableName + "<br/>");
Response.Write("表達式:" + query.Expression.ToString() + "<br/>");
Response.Write("sql:" + query.Provider.ToString() + "<br/>");
上面的代碼執行結果如下:
Provider類型:System.Data.Linq.SqlClient.SqlProvider
數據庫:Northwind
表:dbo.Customers
表達式:Table(Customer).Select(c => c)
sql:SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax] FROM [dbo].[Customers] AS [t0]窗體頂端
窗體底端
撤銷提交
var customer = ctx.Customers.Single(c => c.CustomerID == "AROUT");
customer.ContactName = "zhuye";
customer.Country = "Shanghai";
Response.Write(string.Format("Name:{0},Country:{1}<br/>", customer.ContactName, customer.Country));
customer = ctx.Customers.GetOriginalEntityState(customer);
Response.Write(string.Format("Name:{0},Country:{1}<br/>", customer.ContactName, customer.Country));
上面的代碼執行效果如下:
Name:zhuye,Country:Shanghai
Name:Thomas Hardy,Country:UK
批量操作
下面的代碼會導致提交N次DELETE操作:
var query = from c in ctx.Customers select c;
ctx.Customers.RemoveAll(query);
ctx.SubmitChanges();
應該使用sql語句進行批操作:
string sql = String.Format("delete from {0}", ctx.Mapping.GetTable(typeof(Customer)).TableName);
ctx.ExecuteCommand(sql);
對於批量更新操作也是同樣道理。
本文將會不斷補充其它點滴。最後一篇將會結合分層分布式應用給出一個實際的項目。