Condividi tramite


Procedura: serializzare e deserializzare oggetti (Entity Framework)

I tipi di entità generati dallo strumento generatore Entity Data Model (EdmGen.exe) e dalla procedura guidata di Entity Data Model supportano la serializzazione binaria. Quando si serializza un oggetto in un flusso binario, verranno serializzati anche tutti gli oggetti correlati attualmente caricati nel contesto dell'oggetto. Per ulteriori informazioni, vedere Serializzazione di oggetti (Entity Framework).

L'esempio incluso in questo argomento è basato sul modello Sales di AdventureWorks. Per eseguire il codice incluso in questo esempio, è necessario avere già aggiunto il modello Sales di AdventureWorks al progetto e avere configurato il progetto per l'utilizzo di Entity Framework. A tale scopo, completare le procedure descritte in Procedura: configurare manualmente un progetto di Entity Framework e Procedura: definire manualmente un modello EDM (Entity Framework). È inoltre necessario aggiungere le istruzioni using (Imports in Visual Basic) per gli spazi dei nomi seguenti:

Esempio

In questo esempio un metodo SerializeToBinaryStream esegue una query per l'oggetto Contact per il valore del cognome specificato e restituisce un oggetto MemoryStream binario. MemoryStream contiene un oggetto grafico dell'oggetto Contact e dei relativi oggetti SalesOrderHeader e SalesOrderDetail correlati.

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 = CType(formatter.Deserialize(stream), Contact)
            context.Attach(contact)

            ' Display information for each item 
            ' in the orders that belong to the contact.
            For Each order As SalesOrderHeader In contact.SalesOrderHeader
                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.SalesOrderDetail
                    Console.WriteLine(String.Format("Product:{0}" _
                        + "Quantity: {1}", item.ProductID.ToString(), _
                        item.OrderQty.ToString()))
                Next
            Next
        Catch ex As ApplicationException
            Console.WriteLine(ex.ToString())
        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 BinaryFormatter = New BinaryFormatter()
    Dim stream As MemoryStream = 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.Contact '.Include("SalesOrderHeader.SalesOrderDetail")

        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 ApplicationException("The object query failed", ex)
        Catch ex As EntityCommandExecutionException
            Throw New ApplicationException("The object query failed", ex)
        Catch ex As SerializationException
            Throw New ApplicationException("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.SalesOrderHeader)
            {
                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.SalesOrderDetail)
                {
                    Console.WriteLine(String.Format("Product: {0} "
                        + "Quantity: {1}", item.ProductID.ToString(),
                        item.OrderQty.ToString()));
                }
            }
        }
        catch (ApplicationException ex)
        {
            Console.WriteLine(ex.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.Contact.Include("SalesOrderHeader.SalesOrderDetail");

        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 ApplicationException("The object query failed", ex);
        }
        catch (EntityCommandExecutionException ex)
        {
            throw new ApplicationException("The object query failed", ex);
        }
        catch (SerializationException ex)
        {
            throw new ApplicationException("The object graph could not be serialized", ex);
        }

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

Vedere anche

Altre risorse

Utilizzo di oggetti (attività di Entity Framework)