安裝 LINQ Preview 後,sqlmetal.exe 位於:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\binC:\WINDOWS\Microsoft.NET\Framework\v3.5
sqlmetal /server:myserver /database:northwind /namespace:nwind /code:nwind.cs /language:csharp
參數說明:
/server:資料庫伺服器/database:資料庫名稱/namespace:產生程式碼命名空間/code:輸出 .cs 檔案/language:程式語言
public partial class Northwind : DataContext {
public Table Orders;
public Table Products;
public Table OrderDetails;
// ...
}
partial:C# 2.0 特性,允許分散定義DataContext 才能獲得 LINQ to SQL 支援Table 泛型對應資料表,Class 與 Table 一對一
[Table(Name = "Orders")]
public partial class Order : INotifyPropertyChanging, INotifyPropertyChanged {
private int _OrderID;
private string _CustomerID;
private Nullable _EmployeeID;
// ...
[Column(Storage="_OrderID", DBType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDBGenerated=true)]
public int OrderID { get { return _OrderID; } }
// ...
}
INotifyPropertyChanging/Changed 支援雙向繫結ColumnAttribute 描述欄位對應:Storage(私有欄位)、DBType、IsPrimaryKey、IsDBGeneratedEntitySet/EntityRef(建構子初始化)nwind.cs 至專案Program.cs 撰寫:
using nwind;
using System.Data.DLinq;
class Program {
static void Main() {
Northwind db = new Northwind("Your Connection String");
var q = from c in db.Customers select c;
foreach (var c in q) Console.WriteLine(c.ContactName);
}
}
執行成功!下章將詳細講解 LINQ to SQL 語法。