External mapping file
We can use the SQLMetal command-line tool to generate an external mapping file, using the following methods:
1, Start menu-"VS2008-" vs Tool-"VS2008 command prompt
2, enter the command:
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. In this way, we can get an XML mapping file and C # entity class code under C disk
4. Add the. cs file to the project (put it in the App_Code directory), and then load the mapping file using the following 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. You can do other work as usual now. Using SQLMetal makes it easy to synchronize databases with entities and mapping files. Each time you modify the database structure, removing the tables, stored procedures, and then adding them back to the DBML designer is a hassle.
Handling Null values
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/>");
}
After code execution captures the following SQL is executed:
SELECT COUNT(*) AS [value]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[Region] IS NULL
SELECT [t0].[ReportsTo]
FROM [dbo].[Employees] AS [t0]