다음을 통해 공유


방법: 계층당 하나의 테이블 상속을 사용하여 개체 추가 및 수정(Entity Framework)

이 예제에서는 방법: 계층당 하나의 테이블 상속을 사용하여 모델 정의(Entity Framework) 항목에서 디자인한 EDM(엔터티 데이터 모델)을 사용합니다.

계층당 하나의 테이블 상속 모델을 사용하여 프로젝트를 만들려면

  1. 콘솔 응용 프로그램 프로젝트를 만들고 System.Data.EntitySystem.Runtime.Serialization에 대한 참조를 추가합니다.

  2. 방법: 계층당 하나의 테이블 상속을 사용하여 모델 정의(Entity Framework) 항목에서 설명한 상속 모델에서 빌드한 dll에 대한 참조를 추가합니다.

  3. 방법: 계층당 하나의 테이블 상속을 사용하여 모델 정의(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 파생 형식을 추가하고 Instructor를 수정하려면

  1. SchoolDataEntities 개체 컨텍스트를 인스턴스화합니다.

  2. Instructor 형식의 새 인스턴스를 만들고 Instructor 속성에 데이터를 할당합니다.

  3. AddToPeople 메서드를 사용하여 Instructor의 새 인스턴스를 저장소에 추가합니다. AddToPeople 메서드의 매개 변수는 새 Instructor 인스턴스의 이름입니다.

  4. 변경 내용을 저장합니다.

  5. Student 형식의 새 인스턴스를 만들고 속성을 초기화합니다.

  6. 저장소에 추가하고 변경 내용을 저장합니다.

  7. LastName 속성이 Griffin인 Instructor 인스턴스에 대한 쿼리에 사용할 ObjectParameter를 만듭니다.

  8. 쿼리를 테스트하여 이 속성을 가진 Instructor가 저장소에 있는지 확인합니다.

  9. 지정된 Instructor를 쿼리하고 changeInstructor라는 변수에 할당합니다.

  10. LastName 속성을 Anderson으로 할당하고 변경 내용을 저장합니다.

예제

다음 코드에서는 Instructor 형식 및 Student 형식의 새 인스턴스를 추가합니다. 그런 다음 LastName이 Griffin인 Instructor를 쿼리하고 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());
            }

        }
    }
}

참고 항목

작업

방법: 계층당 하나의 테이블 상속을 사용하여 모델 정의(Entity Framework)
방법: 계층당 하나의 테이블 상속을 사용하여 개체 쿼리 만들기 및 실행(Entity Framework)