HOW TO:加入及修改具有複雜類型的物件 (Entity Framework)
本主題使用 HOW TO:定義具有複雜類型的模型 (Entity Framework) 中所設計的 Entity Data Model。
若要建立應用程式以及在儲存區中加入複雜類型
建立名為 CustomerComplexAddrClient 的主控台應用程式專案。
加入 System.Data.Entity 和 System.Runtime.Serialization 命名空間的參考。
加入從 HOW TO:定義具有複雜類型的模型 (Entity Framework) 主題所述之專案建置之 dll 的參考。
將主題 HOW TO:定義具有複雜類型的模型 (Entity Framework) 中的結構描述加入至與可執行檔相同的資料夾。
建立應用程式組態檔,如底下所示。
將範例程式碼加入至 Program.cs 檔案。
建置及執行專案。
// The following syntax is used in the App.config file.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="CustomerComplexAddressContext"
connectionString="metadata=.;
provider=System.Data.SqlClient;
provider connection string="
Data Source=serverName;
Initial Catalog=CustomerWComplexAddress;
Integrated Security=True;
multipleactiveresultsets=true""
providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
範例
這裡所示的範例程式碼會建立 CCustomer 的實體及複雜類型的 CAddress。CCustomer 和 CAddress 的屬性會初始化。CAddress 會指派給 CCustomer 的 Address 屬性。CCustomer 和 CAddress 都會加入到儲存區,而且會儲存變更。
Option Explicit On
Option Strict On
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports CustomerComplexAddress
Module Module1
Sub Main()
Try
Using objCtx As CustomerComplexAddressContext = _
New CustomerComplexAddressContext()
Dim newCustomer12 As CCustomer = New CCustomer()
newCustomer12.CustomerId = 12
newCustomer12.ContactTitle = "Title 12"
newCustomer12.ContactName = "Contact 12"
newCustomer12.CompanyName = "Company 12"
Dim newAddress12 As CAddress = New CAddress()
newAddress12.StreetAddress = "1121 St"
newAddress12.City = "Redmond"
newAddress12.Region = "WA"
newAddress12.Country = "USA"
newAddress12.PostalCode = "97612"
newAddress12.Phone = "2344567812"
newAddress12.Fax = "3451238712"
newCustomer12.Address = newAddress12
objCtx.AddToCCustomers(newCustomer12)
objCtx.SaveChanges()
End Using
Catch ex As Exception
Console.WriteLine(ex.ToString())
End Try
End Sub
End Module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CustomerComplexAddress;
namespace CustomerComplexAddrClient
{
class Program
{
static void Main(string[] args)
{
try
{
using (CustomerComplexAddressContext objCtx =
new CustomerComplexAddressContext())
{
CCustomer newCustomer10 = new CCustomer();
newCustomer10.CustomerId = 10;
newCustomer10.ContactTitle = "Title 10";
newCustomer10.ContactName = "Contact 10";
newCustomer10.CompanyName = "Company 10";
CAddress newAddress10 = new CAddress();
newAddress10.StreetAddress = "1001 St";
newAddress10.City = "Redmond";
newAddress10.Region = "WA";
newAddress10.Country = "USA";
newAddress10.PostalCode = "97600";
newAddress10.Phone = "2344567890";
newAddress10.Fax = "3451238700";
newCustomer10.Address = newAddress10;
objCtx.AddToCCustomers(newCustomer10);
objCtx.SaveChanges();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
另請參閱
工作
HOW TO:定義具有複雜類型的模型 (Entity Framework)
HOW TO:使用複雜類型來建立和執行物件查詢 (Entity Framework)