使用關聯的應用程式程式碼 (EDM)
實體資料模型 (EDM) 主題實作關聯 (EDM)中設計的物件模型可由用戶端應用程式所使用。EDM 應用程式可以具現化、查詢及保存資料,而不需要 SQL 陳述式。如需詳細資訊,請參閱物件服務概觀 (Entity Framework)。
本主題所示範的應用程式程式碼將說明如何具現化 Customers 和 Orders 實體的關聯,並巡覽 Customers 與 Orders 之間及 Orders 與 OrderLines 之間的關聯。
建立及初始化實體
下列程式碼片段會示範如何針對三種型別的每一種建立一個執行個體:Customers
、Orders
和 OrderLines
。與 OrderInfo
命名空間的連接會在一行程式碼中具現化:OrderInfo orderInfo = new OrderInfo()
。
由於這些實體為可程式化類別,所以當建置類別庫 (Class Library) 時,將會使用提供的建構函式來建立這些實體。請使用 OrderInfo
ObjectContext 的 AddToOrderInfo
方法,將這些實體加入至物件內容。如需詳細資訊,請參閱加入、修改和刪除物件 (Entity Framework)。
下列程式碼區段會建立 Customer
、Order
和 OrderLine
。此程式碼也會具現化 Customer
與 Order
之間及 Order
與 OrderLine
之間的關聯。
在下列程式碼中初始化物件之後,會將這些物件加入至儲存區,並儲存變更。
Dim i As Integer = 0
Dim newCustomer As Customers = _
New Customers()
newCustomer.CustomerId = _
Guid.NewGuid()
newCustomer.Name = "Customer-" + _
i.ToString()
newCustomer.Address = "Address-" + _
i.ToString()
newCustomer.City = "Redmond"
newCustomer.Phone = "123 456-7890"
newCustomer.ZipCode = 98054
Dim newOrder As New Orders()
newOrder.OrderId = i.ToString()
newOrder.Customers = newCustomer
newOrder.ShippingAddress = _
"Address-" + i.ToString()
newOrder.Tax = 0
newOrder.TotalAmount = 0
Dim newOrderLines As OrderLines = New OrderLines()
newOrderLines.OrderLineId = Guid.NewGuid()
newOrderLines.ProductName = "Product-" + _
i.ToString()
newOrderLines.Quantity = 2
newOrderLines.UnitPrice = 67.71
newOrderLines.ExtendedPrice = _
newOrderLines.Quantity * _
newOrderLines.UnitPrice
newOrder.OrderLines.Add(newOrderLines)
orderInfo.AddToCustomers(newCustomer)
orderInfo.AddToOrders(newOrder)
orderInfo.SaveChanges()
int i = 0;
Customers newCustomer = new Customers();
newCustomer.CustomerId = Guid.NewGuid();
newCustomer.Name = "Customer-" + i.ToString();
newCustomer.Address = "Address" + i.ToString();
newCustomer.City = "Redmond";
newCustomer.Phone = "123 456-7890";
newCustomer.ZipCode = 98054;
Orders newOrder = new Orders();
newOrder.OrderId = i.ToString();
newOrder.Customers = newCustomer;
newOrder.ShippingAddress = "Address-" +
i.ToString();
newOrder.Tax = 0;
newOrder.TotalAmount = 0;
OrderLines newOrderLines = new OrderLines();
newOrderLines.OrderLineId = Guid.NewGuid();
newOrderLines.ProductName = "Product-" +
i.ToString();
newOrderLines.Quantity = 2;
newOrderLines.UnitPrice = (decimal)67.70;
newOrderLines.ExtendedPrice =
newOrderLines.Quantity *
newOrderLines.UnitPrice;
newOrder.OrderLines.Add(newOrderLines);
orderInfo.AddToCustomers(newCustomer);
orderInfo.AddToOrders(newOrder);
orderInfo.SaveChanges();
巡覽關聯
存取與 Customers
相關的 Orders
以及與 Orders
相關的 OrderLines
,其方式是搭配設計結構描述內指定的 NavigationProperty 來使用關聯。如需導覽屬性的詳細資訊,請參閱 NavigationProperty 項目(EntityType CSDL)。
實作關聯 (EDM)中有描述此範例使用的所有屬性。
下列 foreach 迴圈 (Loop) 會擷取 Customer.Orders
NavigationProperty 中所包含的 Orders
集合以及 Order.OrderLines
NavigationProperty 中所包含的每個 OrderLines
。您必須在巡覽這些屬性之前呼叫 Load 方法。Load 方法會取得資料庫中的項目 (Load 方法的替代方式是使用 Orders
和 OrderLines
的 Source
屬性)。
For Each customer In orderInfo.Customers
Console.WriteLine("Customer: " + customer.Name)
' If customer has orders, load orders.
customer.Orders.Load()
For Each order In orderInfo.Orders
Console.WriteLine(vbTab + "Order#: " _
+ order.OrderId)
' Load orderlines
order.OrderLines.Load()
For Each orderline In order.OrderLines
Console.WriteLine(vbTab + vbTab + _
orderline.ProductName)
Next
Next
foreach (Customers customer in orderInfo.Customers)
{
Console.WriteLine("Customer: " +
customer.Name);
//If customer has orders, load orders.
customer.Orders.Load();
foreach (Orders order in customer.Orders)
{
Console.WriteLine("\t" + order.OrderId);
// Load OrderLines.
order.OrderLines.Load();
foreach (OrderLines orderLine in
order.OrderLines)
Console.WriteLine(
"\t\t" + orderLine.ProductName);
}
}
應用程式組態中的連接
使用 OrderInfo
物件模型的實體和關聯需要連接資料庫,此資料庫會針對 Entity Data Model (EDM) 上建置的應用程式儲存資料。開啟應用程式程式碼所使用的連接類似於開啟 SQL 連接。除了 SQL 連接用來識別此模型使用之資料庫和伺服器的連接字串以外,此連接還需要 EDM 結構描述的路徑及對應規格。在此範例中,app.config 檔案包含連接字串及中繼資料的位置。app.config 的內容如下列程式碼所示:
?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="OrderInfo"
connectionString='Metadata=.;
Provider=System.Data.SqlClient;
Provider Connection String="server=serverName;
database=OrderInfo;Integrated Security=true;
Connection Timeout=5;multipleactiveresultsets=true"'
providerName="System.Data.EntityClient"/>
</connectionStrings>
</configuration>
範例
用來執行上一個區段的完整程式碼顯示於下列範例中。Helper 方法 ComputeOrder
****的呼叫是由程式碼最後一個區段的註解所識別。如需 Helper 方法的實作,請參閱 HOW TO:自訂產生的資料物件 (Entity Framework)。
Imports OrderInfoModel
Module Module1
Sub Main()
Try
Using orderInfo As OrderInfo = New OrderInfo()
For Each customer In orderInfo.Customers
Console.WriteLine("Customer: " + customer.Name)
' If customer has orders, load orders.
customer.Orders.Load()
For Each order In orderInfo.Orders
Console.WriteLine(vbTab + "Order#: " _
+ order.OrderId)
' Load orderlines
order.OrderLines.Load()
For Each orderline In order.OrderLines
Console.WriteLine(vbTab + vbTab + _
orderline.ProductName)
Next
For Each order2 In orderInfo.Orders
Console.WriteLine("Order#: " + _
order2.OrderId)
' Display OrderLines products and quantities.
order2.OrderLines.Load()
For Each orderline2 In order2.OrderLines
Console.WriteLine(vbTab + "{0} " + _
"UnitPrice: ${1} " + _
"Quantity: {2}", _
orderline2.ProductName, _
orderline2.UnitPrice, _
orderline2.Quantity)
' Open the commented code in this
' section to use the ComputeOrder
' helper method defined in the topic
' Helper Methods (EDM).
'Console.WriteLine(vbTab + vbTab + _
'vbTab + "Total Order # {0}: " + _
'"${1} Including ${2} tax", _
'order2.OrderId, _
'Decimal.Round( _
'order2.ComputeOrder(), _
'2), _
'order2.Tax)
Next
Next
Next
Next
' Set to True to add entities.
If False Then
Dim i As Integer = 0
Dim newCustomer As Customers = _
New Customers()
newCustomer.CustomerId = _
Guid.NewGuid()
newCustomer.Name = "Customer-" + _
i.ToString()
newCustomer.Address = "Address-" + _
i.ToString()
newCustomer.City = "Redmond"
newCustomer.Phone = "123 456-7890"
newCustomer.ZipCode = 98054
Dim newOrder As New Orders()
newOrder.OrderId = i.ToString()
newOrder.Customers = newCustomer
newOrder.ShippingAddress = _
"Address-" + i.ToString()
newOrder.Tax = 0
newOrder.TotalAmount = 0
Dim newOrderLines As OrderLines = New OrderLines()
newOrderLines.OrderLineId = Guid.NewGuid()
newOrderLines.ProductName = "Product-" + _
i.ToString()
newOrderLines.Quantity = 2
newOrderLines.UnitPrice = 67.71
newOrderLines.ExtendedPrice = _
newOrderLines.Quantity * _
newOrderLines.UnitPrice
newOrder.OrderLines.Add(newOrderLines)
orderInfo.AddToCustomers(newCustomer)
orderInfo.AddToOrders(newOrder)
orderInfo.SaveChanges()
End If
End Using
Catch ex As Exception
Console.WriteLine(ex.Message.ToString() + "\n" + _
ex.InnerException.ToString())
End Try
End Sub
End Module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OrderInfoModel;
namespace Associations_CS
{
class Program
{
static void Main(string[] args)
{
try
{
using (OrderInfo orderInfo = new OrderInfo())
{
foreach (Customers customer in orderInfo.Customers)
{
Console.WriteLine("Customer: " +
customer.Name);
//If customer has orders, load orders.
customer.Orders.Load();
foreach (Orders order in customer.Orders)
{
Console.WriteLine("\t" + order.OrderId);
// Load OrderLines.
order.OrderLines.Load();
foreach (OrderLines orderLine in
order.OrderLines)
Console.WriteLine(
"\t\t" + orderLine.ProductName);
}
}
foreach (Orders order in orderInfo.Orders)
{
Console.WriteLine("Order: " + order.OrderId);
// Display OrderLines products and quantities.
order.OrderLines.Load();
foreach (OrderLines orderLine in
order.OrderLines)
Console.WriteLine(
"\t{0} UnitPrice: ${1} Quantity: {2}",
orderLine.ProductName,
orderLine.UnitPrice,
orderLine.Quantity );
// Open the commented code in this section to
// use the ComputeOrder helper method defined
// in the topic Helper Methods (EDM).
/*Console.WriteLine("\t\t\tTotal Order #{0}: " +
"${1} Including ${2} tax",
order.OrderId,
Decimal.Round(
order.ComputeOrder(), 2),
order.Tax); */
}
if(false) // Set to true to add entities.
{
int i = 0;
Customers newCustomer = new Customers();
newCustomer.CustomerId = Guid.NewGuid();
newCustomer.Name = "Customer-" + i.ToString();
newCustomer.Address = "Address" + i.ToString();
newCustomer.City = "Redmond";
newCustomer.Phone = "123 456-7890";
newCustomer.ZipCode = 98054;
Orders newOrder = new Orders();
newOrder.OrderId = i.ToString();
newOrder.Customers = newCustomer;
newOrder.ShippingAddress = "Address-" +
i.ToString();
newOrder.Tax = 0;
newOrder.TotalAmount = 0;
OrderLines newOrderLines = new OrderLines();
newOrderLines.OrderLineId = Guid.NewGuid();
newOrderLines.ProductName = "Product-" +
i.ToString();
newOrderLines.Quantity = 2;
newOrderLines.UnitPrice = (decimal)67.70;
newOrderLines.ExtendedPrice =
newOrderLines.Quantity *
newOrderLines.UnitPrice;
newOrder.OrderLines.Add(newOrderLines);
orderInfo.AddToCustomers(newCustomer);
orderInfo.AddToOrders(newOrder);
orderInfo.SaveChanges();
}
}
}
catch (System.Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}