共用方式為


HOW TO:加入及修改具有每個階層的資料表繼承的物件 (Entity Framework)

此範例使用 HOW TO:使用每個階層的資料表繼承來定義模型 (Entity Framework) 主題中所設計的 Entity Data Model (EDM)。

若要使用每個階層的資料表繼承模型來建立專案

  1. 建立主控台應用程式專案,並加入 System.Data.EntitySystem.Runtime.Serialization 的參考。

  2. 加入從 HOW TO:使用每個階層的資料表繼承來定義模型 (Entity Framework) 主題中之繼承模型建置而來之 dll 的參考。

  3. 將主題 HOW TO:使用每個階層的資料表繼承來定義模型 (Entity Framework) 中的結構描述加入至與 SchoolDataClient 可執行檔相同的資料夾。

  4. 加入具有底下範例內容的應用程式組態檔。

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <connectionStrings><add name="SchoolDataLibContainer" 
       connectionString=
       "metadata=res://*/SchoolDataLib.csdl|
       res://*/SchoolDataLib.ssdl|
       res://*/SchoolDataLib.msl;provider=System.Data.SqlClient;
       provider connection string=&quot;
       Data Source=localhost;
       Initial Catalog=SchoolData;Integrated Security=True;
       MultipleActiveResultSets=True&quot;" 
       providerName="System.Data.EntityClient" />
      </connectionStrings>
    </configuration>
    

若要加入新的 Instructor 和 Student 衍生型別 (Derived Type),並修改 Instructor

  1. 具現化 SchoolDataEntities 物件內容。

  2. 建立 Instructor 型別的新執行個體,並指派資料給 Instructor 屬性。

  3. 使用 AddToPeople 方法將新的 Instructor 執行個體加入到儲存區。AddToPeople 方法的參數是新 Instructor 執行個體的名稱。

  4. 儲存變更。

  5. 建立 Student 型別的新執行個體及初始化屬性。

  6. 加入到儲存區,並儲存變更。

  7. 建立要在 Instructor 執行個體的查詢中搭配等於 Griffin 的 LastName 屬性使用的 ObjectParameter

  8. 測試查詢來確認具有這個屬性的 Instructor 已經存在於儲存區中。

  9. 查詢指定的 Instructor,並將它指派給名為 changeInstructor 的變數。

  10. LastName 屬性指派給 Anderson,並儲存變更。

範例

下列程式碼會加入 Instructor 型別和 Student 型別的新執行個體。接下來,它會查詢 Instructor 中的 LastName Griffin,並將 LastName 屬性變更為 Anderson。

Option Explicit On
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml
Imports System.Xml.Linq
Imports System.Text
Imports SchoolDataLib

Module Module1

    Sub Main()
        Try
            Using objectContext As SchoolDataLibContainer =
                                      New SchoolDataLibContainer()
                ' Display departments and administrators.
                For Each dept As Department In objectContext.Departments
                    Console.WriteLine("School: {0} Budget: {1}", _
                            dept.Name, dept.Budget)

                    ' Load associated contact reference if any.
                    dept.AdministratorReference.Load()
                    If dept.Administrator IsNot Nothing Then
                        Console.WriteLine("Administrator: {0} {1}", _
                            dept.Administrator.FirstName, _
                            dept.Administrator.LastName)
                    End If
                Next

                For Each eDept As DeptEngineering In _
                        objectContext.Departments.OfType(Of DeptEngineering)()
                    Console.WriteLine("{0} LabBudget: {1} FiberOp Budget: {2}", _
                        eDept.Name, eDept.LabBudget.ToString(), _
                        eDept.FiberOpticsBudget.ToString())
                Next

                Dim countDept As Integer = 0
                Dim newDept As DeptEngineering = New DeptEngineering()

                For Each dept As Department In objectContext.Departments
                    countDept = countDept + 1
                Next

                newDept.DepartmentID = countDept + 1
                newDept.Name = "Engineering School " + (countDept + 1).ToString()
                newDept.StartDate = DateTime.Now
                newDept.FiberOpticsBudget = 250000.0
                newDept.LabBudget = 400000.0
                newDept.Budget = newDept.FiberOpticsBudget + newDept.LabBudget

                ' Create new contact item to be 
                ' added as school administrator.
                Dim countPerson As Integer = 0
                For Each pers As Person In objectContext.People
                    countPerson = countPerson + 1
                Next

                Dim newAdmin As Administrator = New Administrator()
                newAdmin.PersonID = countPerson + 1
                newAdmin.FirstName = "Tony"
                newAdmin.LastName = "Allen"
                newAdmin.AdminDate = DateTime.Now - New TimeSpan(2000, 0, 0, 0)

                ' Assign the contact to Administrator property.
                newDept.Administrator = newAdmin

                ' Add admin and school to object context.
                objectContext.AddToPeople(newAdmin)
                objectContext.AddToDepartments(newDept)

                objectContext.SaveChanges()
            End Using

        Catch ex As System.Data.MappingException
            Console.WriteLine(ex.ToString())
        Catch ex As System.Data.CommandExecutionException
            Console.WriteLine(ex.ToString())
        Catch ex As System.Data.UpdateException
            Console.WriteLine(ex.ToString())
        End Try

    End Sub
End Module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SchoolDataLibTPH;
using System.Data.Objects;
namespace SchoolDataLib
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Add new Instructor.
                using (SchoolDataLibContainer objectContext =
                                      new SchoolDataLibContainer())
                {
                    Instructor newInstructor =
                        new Instructor();
                    newInstructor.PersonID =
                            objectContext.People.Count<Person>() + 1;
                    newInstructor.FirstName = "Satomi";
                    newInstructor.LastName = "Hayakawa";

                    newInstructor.HireDate = DateTime.Now;

                    objectContext.AddToPeople(newInstructor);
                    objectContext.SaveChanges();

                    // Add new Student.
                    Student newStudent = new Student();
                    int count = objectContext.People.Count<Person>();
                    newStudent.PersonID = count + 1;
                    newStudent.FirstName = "Uzi";
                    newStudent.LastName = "Hefetz";
                    newStudent.EnrollmentDate = DateTime.Now;


                    objectContext.AddToPeople(newStudent);
                    objectContext.SaveChanges();

                    // Change the last name of an instructor.
                    ObjectParameter param =
                                  new ObjectParameter("p", "Hayakawa");
                    if (0 != objectContext.People.OfType<Instructor>().
                                  Where("it.LastName = @p",
                                  param).Count<Instructor>())
                    {
                        Instructor changeInstructor = 
                              objectContext.People.
                              OfType<Instructor>().Where(
                             "it.LastName = @p", param).First();
                        changeInstructor.LastName = "Anderson";
                        objectContext.SaveChanges();

                    }

                    objectContext.Connection.Close();
                }
            }

            catch (System.Data.MappingException e)
            {
                Console.WriteLine(e.ToString());
            }
            catch (System.Data.UpdateException e)
            {
                Console.WriteLine(e.ToString());
            }

        }
    }
}

另請參閱

工作

HOW TO:使用每個階層的資料表繼承來定義模型 (Entity Framework)
HOW TO:使用每個階層的資料表繼承來建立和執行物件查詢 (Entity Framework)