視頻示範:http://u.115.com/file/f2e3bc874c
本演練提供了複雜性最低的基本端對端 LINQ to SQL 方案。您將建立一個可為樣本 Northwind 資料庫中的 Customers 表建模的實體類。 然後您將建立一個簡單查詢,用於列出位於倫敦的客戶。
本演練在設計上是面向代碼的,以協助說明 LINQ to SQL 概念。 一般來說,您會使用物件關聯式設計工具來建立物件模型。 有關更多資訊,請參見物件關聯式設計工具(O/R 設計工具)。
建立LINQ to SQL解決方案
此任務為第一項任務,在此任務中,您要建立一個 Visual Studio 解決方案,此方案套件含產生和運行 LINQ to SQL 項目所必需的引用。
1、 在 Visual Studio 的[檔案] 功能表上指向“建立”,然後單擊“項目”。
2、 在“建立項目”對話方塊的“項目類型”窗格中,單擊“Visual C#”。
3、 在“模板”窗格中,單擊“控制台應用程式”。
4、 在“名稱”框中,鍵入 LinqConsoleApp。
5、 在“位置”框中,確認要用於儲存專案檔的位置。
6、 單擊“確定”。
添加LINQ引用和指令
本演練用到預設情況下您的項目中可能未安裝的程式集。 如果在您的項目中未將 System.Data.Linq 作為引用列出(在“方案總管”中展開“引用”節點),請按照以下步驟中的說明添加它。
1、 在“方案總管”中,右擊“引用”,然後單擊“添加引用”。
2、 在“添加引用”對話方塊中,依次單擊“.NET”、System.Data.Linq 程式集和“確定”。
此程式集即被添加到項目中。
3、 在“Program.cs”的頂部添加以下指令:
using System.Data.Linq; using System.Data.Linq.Mapping; using System.Data.Linq;using System.Data.Linq.Mapping;
將類映射到資料庫表
在此步驟中,您將建立一個類,並將其映射到資料庫表。 這樣的類稱為“實體類”。 請注意,只需添加 TableAttribute 屬性即可完成映射。 Name 屬性指定資料庫中的表的名稱。
將下面的代碼鍵入或粘貼到 Program.cs 中緊靠在 Program 類聲明上方的位置:
[Table(Name = "Customers")] public class Customer { } [Table(Name = "Customers")]public class Customer{}
在類中指定用於表示資料庫列的屬性
在此步驟中,您要完成幾項任務。
您要使用 ColumnAttribute 屬性 (Attribute) 指定實體類中的 CustomerID 和 City 屬性 (Property) 表示資料庫表中的列。
您要指定 CustomerID 屬性工作表示資料庫中的主鍵列。
您要指定 _CustomerID 和 _City 欄位用作私人儲存欄位。 然後,LINQ to SQL 就可以直接儲存和檢索值,而不用使用可能包含商務邏輯的公用訪問器。
表示兩個資料庫列的特性
將下面的代碼鍵入或粘貼到 Program.cs 中 Customer 類的大括弧內。
private string _CustomerID; [Column(IsPrimaryKey = true, Storage = "_CustomerID")] public string CustomerID { get { return this._CustomerID; } set { this._CustomerID = value; } } private string _City; [Column(Storage = "_City")] public string City { get { return this._City; } set { this._City = value; } } private string _CustomerID;[Column(IsPrimaryKey = true, Storage = "_CustomerID")]public string CustomerID{ get { return this._CustomerID; } set { this._CustomerID = value; }}private string _City;[Column(Storage = "_City")]public string City{ get { return this._City; } set { this._City = value; }}
指定與Northwind資料庫的串連
在此步驟中,使用 DataContext 對象在基於代碼的資料結構與資料庫本身之間建立串連。 DataContext 是您從資料庫中檢索對象和提交更改的主要通道。
您還可以針對資料庫中的 Customers 表聲明 Table<Customer> 作為查詢的類型化邏輯表。 您將在後續步驟中建立和執行這些查詢。
將下面的代碼鍵入或粘貼到 Main 方法中。
請注意,假定 Northwind.mdf 檔案位於 linqtest5 檔案夾中。 有關更多資訊,請參見本演練前面介紹的“先決條件”一節。
// Use a connection string. DataContext db = new DataContext(@"C:\linqtest5\Northwind.mdf"); // Get a typed table to run queries. Table<Customer> Customers = db.GetTable<Customer>(); // Use a connection string.DataContext db = new DataContext(@"C:\linqtest5\Northwind.mdf");// Get a typed table to run queries.Table<Customer> Customers = db.GetTable<Customer>();
建立簡單查詢
在此步驟中,您將建立一個查詢,尋找資料庫中的 Customers 表內的哪些客戶位於倫敦。 此步驟中的查詢代碼只描述查詢,它不執行查詢。 這種方法稱為“順延強制 ”。 有關更多資訊,請參見 LINQ 查詢簡介 (C#)。
您還將產生一個日誌輸出,顯示 LINQ to SQL 產生的 SQL 命令。 此日誌記錄功能(使用 Log)對調試有協助,並有助於確定發送給資料庫的命令是否準確地表示您的查詢。
將下面的代碼鍵入或粘貼到 Table<Customer> 聲明後面的 Main 方法中。
// Attach the log to show generated SQL. db.Log = Console.Out; // Query for customers in London. IQueryable<Customer> AllCustomers = from Customer in Customers where Customer.City == "London" select Customer; // Attach the log to show generated SQL.db.Log = Console.Out;// Query for customers in London.IQueryable<Customer> AllCustomers = from Customer in Customers where Customer.City == "London" select Customer;
執行查詢
在此步驟中,您將實際執行查詢。您在前面步驟中建立的查詢運算式只有在需要結果時才會進行計算。當您開始 foreach 迭代時,將會針對資料庫執行 SQL 命令,並將對象具體化。
1、 將下面的代碼鍵入或粘貼到 Main 方法的末尾(在查詢說明之後)。
foreach (Customer Customer in AllCustomers) { Console.WriteLine("ID={0}, City={1}", Customer.CustomerID, Customer.City); } // Prevent console window from closing. Console.ReadLine(); foreach (Customer Customer in AllCustomers){ Console.WriteLine("ID={0}, City={1}", Customer.CustomerID, Customer.City);}// Prevent console window from closing.Console.ReadLine();
2、 按 F5 調試該應用程式。
說明
如果您的應用程式產生執行階段錯誤,請參見 通過演練學習 (LINQ to SQL) 中的“疑難解答”一節。
3、 控制台視窗中的查詢結果應顯示如下:
SELECT [t0].[CustomerID], [t0].[City] FROM [Customers] AS [t0] WHERE [t0].[City] = @p0 -- @p0: Input NVarChar (Size = 6; Prec = 0; Scale = 0) [London] -- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.1 ID=AROUT, City=London ID=BSBEV, City=London ID=CONSH, City=London ID=EASTC, City=London ID=NORTS, City=London ID=SEVES, City=London SELECT [t0].[CustomerID], [t0].[City]FROM [Customers] AS [t0]WHERE [t0].[City] = @p0-- @p0: Input NVarChar (Size = 6; Prec = 0; Scale = 0) [London]-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.1ID=AROUT, City=LondonID=BSBEV, City=LondonID=CONSH, City=LondonID=EASTC, City=LondonID=NORTS, City=LondonID=SEVES, City=London
4、 在控制台視窗中按 Enter 以關閉應用程式。
完整代碼
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Linq; using System.Data.Linq.Mapping; namespace Demo02 { [Table(Name = "Customers")] public class Customer { private string _CustomerID; [Column(IsPrimaryKey = true, Storage = "_CustomerID")] public string CustomerID { get { return this._CustomerID; } set { this._CustomerID = value; } } private string _City; [Column(Storage = "_City")] public string City { get { return this._City; } set { this._City = value; } } } class Program { static void Main(string[] args) { // Use a connection string. DataContext db = new DataContext(@"C:\linqtest5\Northwind.mdf"); // Get a typed table to run queries. Table<Customer> Customers = db.GetTable<Customer>(); // Attach the log to show generated SQL. db.Log = Console.Out; // Query for customers in London. IQueryable<Customer> AllCustomers = from Customer in Customers where Customer.City == "London" select Customer; foreach (Customer Customer in AllCustomers) { Console.WriteLine("ID={0}, City={1}", Customer.CustomerID, Customer.City); } // Prevent console window from closing. Console.ReadLine(); } } }