(016):[演練]建立簡單物件模型和LINQ查詢(C#)

My_Jackbase發表於2013-12-11


視訊演示: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;

將類對映到資料庫表
在此步驟中,您將建立一個類,並將其對映到資料庫表。 這樣的類稱為“實體類”。 請注意,只需新增 TableAttribute 屬性即可完成對映。 Name 屬性指定資料庫中的表的名稱。
將下面的程式碼鍵入或貼上到 Program.cs 中緊靠在 Program 類宣告上方的位置:

[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;
    }
}

指定與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>();

建立簡單查詢
在此步驟中,您將建立一個查詢,查詢資料庫中的 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;

執行查詢
在此步驟中,您將實際執行查詢。您在前面步驟中建立的查詢表示式只有在需要結果時才會進行計算。當您開始 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();

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

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();
        }
    }
}








相關文章