방법: 개체와 이진 스트림 간의 serialize 및 deserialize(Entity Framework)

EDM(엔터티 데이터 모델 ) 생성기 도구(EdmGen.exe)와 엔터티 데이터 모델 마법사에서 생성된 엔터티 형식은 이진 serialization을 지원합니다. 개체를 이진 스트림으로 serialize하면 개체 컨텍스트에 현재 로드된 모든 관련 개체도 serialize됩니다. 자세한 내용은 개체 Serialize(Entity Framework)를 참조하십시오.

이 항목의 예제는 Adventure Works Sales 모델을 기반으로 합니다. 이 예제의 코드를 실행하려면 프로젝트에 AdventureWorks Sales 모델을 추가하고 Entity Framework를 사용하도록 프로젝트를 구성해야 합니다. 이렇게 하려면 방법: Entity Framework 프로젝트 수동 구성방법: 수동으로 모델 및 매핑 파일 정의(Entity Framework)의 절차를 수행합니다. 다음 네임스페이스에 대한 using 문(Visual Basic에서는 Imports)도 추가해야 합니다.

예제

이 예제에서는 SerializeToBinaryStream 메서드가 지정된 성 값에 대해 Contact 개체를 쿼리한 다음 이진 MemoryStream을 반환합니다. MemoryStream에는 Contact 개체 및 관련 SalesOrderHeaderSalesOrderDetail 개체에 대한 개체 그래프가 포함됩니다.

Public Shared Sub ReadFromBinaryStream()
    Dim formatter As New BinaryFormatter()
    Using context As New AdventureWorksEntities()
        Try
            ' Get the object graph for the selected customer 
            ' as a binary stream. 
            Dim stream As MemoryStream = SerializeToBinaryStream("Adams")

            ' Read from the begining of the stream. 
            stream.Seek(0, SeekOrigin.Begin)

            ' Deserialize the customer graph from the binary stream 
            ' and attach to an ObjectContext. 
            Dim contact As Contact = DirectCast(formatter.Deserialize(stream), Contact)
            context.Attach(contact)

            ' Display information for each item 
            ' in the orders that belong to the first contact. 
            For Each order As SalesOrderHeader In contact.SalesOrderHeaders
                Console.WriteLine(String.Format("PO Number: {0}", order.PurchaseOrderNumber))
                Console.WriteLine(String.Format("Order Date: {0}", order.OrderDate.ToString()))
                Console.WriteLine("Order items:")
                For Each item As SalesOrderDetail In order.SalesOrderDetails
                    Console.WriteLine(String.Format("Product: {0}, Quantity: {1}", _
                                                      item.ProductID.ToString(), item.OrderQty.ToString()))
                Next
            Next
        Catch ex As SerializationException
            Console.WriteLine("The object graph could not be deserialized from " & _
                              "the binary stream because of the following error:")
            Console.WriteLine(ex.ToString())
        End Try
    End Using
End Sub
Private Shared Function SerializeToBinaryStream(ByVal lastName As String) As MemoryStream
    Dim formatter As New BinaryFormatter()
    Dim stream As New MemoryStream()

    Using context As New AdventureWorksEntities()
        ' Specify a timeout for queries in this context, in seconds. 
        context.CommandTimeout = 120

        ' Define a customer contact. 
        Dim customer As Contact

        ' Create a Contact query with a path that returns 
        ' orders and items for a contact. 
        Dim query As ObjectQuery(Of Contact) = context.Contacts.Include("SalesOrderHeaders.SalesOrderDetails")

        Try
            ' Return the first contact with the specified last name 
            ' along with its related orders and items. 
            customer = query.Where("it.LastName = @lastname", New ObjectParameter("lastname", lastName)).First()

            ' Serialize the customer object graph. 
            formatter.Serialize(stream, customer)
        Catch ex As EntitySqlException
            Throw New InvalidOperationException("The object query failed", ex)
        Catch ex As EntityCommandExecutionException
            Throw New InvalidOperationException("The object query failed", ex)
        Catch ex As SerializationException
            Throw New InvalidOperationException("The object graph could not be serialized", ex)
        End Try

        ' Return the streamed object graph. 
        Return stream
    End Using
End Function
public static void ReadFromBinaryStream()
{
    BinaryFormatter formatter = new BinaryFormatter();
    using (AdventureWorksEntities context = new AdventureWorksEntities())
    {
        try
        {
            // Get the object graph for the selected customer
            // as a binary stream.
            MemoryStream stream = SerializeToBinaryStream(@"Adams");

            // Read from the begining of the stream.
            stream.Seek(0, SeekOrigin.Begin);

            // Deserialize the customer graph from the binary stream
            // and attach to an ObjectContext.
            Contact contact = (Contact)formatter.Deserialize(stream);
            context.Attach(contact);

            // Display information for each item 
            // in the orders that belong to the first contact.
            foreach (SalesOrderHeader order in contact.SalesOrderHeaders)
            {
                Console.WriteLine(String.Format("PO Number: {0}",
                    order.PurchaseOrderNumber));
                Console.WriteLine(String.Format("Order Date: {0}",
                    order.OrderDate.ToString()));
                Console.WriteLine("Order items:");
                foreach (SalesOrderDetail item in order.SalesOrderDetails)
                {
                    Console.WriteLine(String.Format("Product: {0} "
                        + "Quantity: {1}", item.ProductID.ToString(),
                        item.OrderQty.ToString()));
                }
            }
        }

        catch (SerializationException ex)
        {
            Console.WriteLine("The object graph could not be deserialized from "
                          + "the binary stream because of the following error:");
            Console.WriteLine(ex.ToString());
        }
    }
}
private static MemoryStream SerializeToBinaryStream(string lastName)
{
    BinaryFormatter formatter = new BinaryFormatter();
    MemoryStream stream = new MemoryStream();

    using (AdventureWorksEntities context = new AdventureWorksEntities())
    {
        // Specify a timeout for queries in this context, in seconds.
        context.CommandTimeout = 120;

        // Define a customer contact.
        Contact customer;

        // Create a Contact query with a path that returns 
        // orders and items for a contact.
        ObjectQuery<Contact> query =
            context.Contacts.Include("SalesOrderHeaders.SalesOrderDetails");

        try
        {
            // Return the first contact with the specified last name
            // along with its related orders and items.
            customer = query.Where("it.LastName = @lastname",
                new ObjectParameter("lastname", lastName)).First();

            // Serialize the customer object graph.
            formatter.Serialize(stream, customer);
        }
        catch (EntitySqlException ex)
        {
            throw new InvalidOperationException("The object query failed", ex);
        }
        catch (EntityCommandExecutionException ex)
        {
            throw new InvalidOperationException("The object query failed", ex);
        }
        catch (SerializationException ex)
        {
            throw new InvalidOperationException("The object graph could not be serialized", ex);
        }

        // Return the streamed object graph.
        return stream;
    }
}

참고 항목

개념

개체 사용(Entity Framework)