若要使用在應用程式程式碼的相關主題中所設計和建置的 Northwind 物件模型,請加入此 DLL 的參考及指定 NorthwindLib 命名空間的 using 指示詞。 這些類型的命名空間將可以在應用程式程式碼中使用,而不需要 SQL 語法。
組態檔和連接字串
使用此物件模型需要連接到儲存應用程式資料的資料庫。 此外,也需要讓實體連接到從結構描述建置之 DLL 所提供的執行階段物件。
exe.config 檔案包含一個連接字串,此字串是用來連接 SQL Server 資料庫及建立實體連接。 當使用實體連接時,可以從程式碼存取物件模型中的實體和關聯。
此連接字串必須由開發人員加入到 exe.config 檔。 這個應用程式會指定 Northwind 類別。 providerName="System.Data.EntityClient" 指派會指定一個實體連接,該連接使用了「Northwind 對應規格」中所定義的對應結構描述。
此連接字串也會識別 SQL 連接所使用的伺服器:提供者 connection string="server=servername"。
下列範例顯示 exe.config 檔的內容。
?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Northwind"
connectionString='Metadata=.;
Provider=System.Data.SqlClient;
Provider Connection String="server=servername;
database=Northwind;Integrated Security=true;
Connection Timeout=5;multipleactiveresultsets=true"'
providerName="System.Data.EntityClient"/>
</connectionStrings>
</configuration>
中繼資料 (其中包含概念結構描述、儲存中繼資料和對應規格) 的路徑是由 Metadata=. 指派所指示。 在此範例中,檔案位於與可執行檔相同的資料夾內,因此此路徑是由句號 (.) 所指定, 如同 Metadata=. 語法所示。 如果結構描述和對應檔不在相同的資料夾中,您必須指定完整路徑。
附註 |
|---|
此連接字串會將 Multiple Active Result Set (MARS) 設定為 true,因為當相同連接上已經開啟另一個資料讀取器時,會需要這樣的設定來叫用關聯上的 Load 方法。 |
應用程式程式碼
下列程式碼會使用概念結構描述中所定義,且對應至對應規格內之儲存中繼資料的實體和關聯。 如需此資料模型的詳細資料,請參閱 Northwind 模型 (EDM)。 將會開啟一個 EntityConnection,此連接會連接到 Northwind 概念結構描述 (EDM) 主題中所定義之概念結構描述所建置的 ObjectContext。 NorthwindLib 命名空間中的實體和關聯是用來顯示實體的屬性 (例如銷售訂單識別碼)、尋找實體之間之關聯中的客戶、顯示產品,以及依照關聯尋找及顯示與產品有關的產品分類。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NorthwindLib;
namespace NorthwindClient
{
class Program
{
static void Main(string[] args)
{
try
{
using (NorthwindLib.Northwind DB = new Northwind())
{
foreach (SalesOrder salesOrder in DB.SalesOrders)
{
salesOrder.CustomerReference.Load();
Console.WriteLine(
"Customer Contact: {0} ** OrderID: {1}",
salesOrder.Customer.ContactName,
salesOrder.OrderID.ToString());
}
foreach (Product product in DB.Products)
{
product.CategoryReference.Load();
Console.WriteLine(" Product: " +
product.ProductName +
" ** Category: " +
product.CategoryReference.Value.CategoryName);
}
DB.Connection.Close();
}
}
catch (System.Data.MappingException e)
{
Console.WriteLine(e.ToString());
}
catch (System.Data.CommandExecutionException e)
{
Console.WriteLine(e.ToString());
}
}
}
}
附註