Cómo: Adjuntar una entidad existente a DataServiceContext (WCF Data Services)

Cuando una entidad ya existe en un servicio de datos, la biblioteca de cliente de WCF Data Services le permite adjuntar un objeto que representa directamente la entidad en la clase DataServiceContext sin ejecutar una consulta primero. Para obtener más información, vea Actualizar el servicio de datos (WCF Data Services).

En el ejemplo de este tema se usan el servicio de datos de ejemplo Northwind y las clases del servicio de datos del cliente generadas automáticamente. Se crean este servicio y las clases de datos del cliente al completar el tutorial rápido de WCF Data Services.

Ejemplo

En el ejemplo siguiente se muestra cómo crear un objeto Customer existente que contiene cambios que se van a guardar en el servicio de datos. Se adjunta el objeto al contexto y se llama al método UpdateObject para marcar el objeto adjunto como Modified antes de llamar al método SaveChanges.

' Create the DataServiceContext using the service URI.
Dim context = New NorthwindEntities(svcUri)

' Define an existing customer to attach, including the key.
Dim customer As Customer = _
    customer.CreateCustomer("ALFKI", "Alfreds Futterkiste")

' Set current property values.
customer.Address = "Obere Str. 57"
customer.City = "Berlin"
customer.PostalCode = "12209"
customer.Country = "Germany"

' Set property values to update.
customer.ContactName = "Peter Franken"
customer.ContactTitle = "Marketing Manager"
customer.Phone = "089-0877310"
customer.Fax = "089-0877451"

Try
    ' Attach the existing customer to the context and mark it as updated.
    context.AttachTo("Customers", customer)
    context.UpdateObject(customer)

    ' Send updates to the data service.
    context.SaveChanges()
Catch ex As DataServiceClientException
    Throw New ApplicationException( _
            "An error occurred when saving changes.", ex)
End Try
// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

// Define an existing customer to attach, including the key.
Customer customer = 
    Customer.CreateCustomer("ALFKI", "Alfreds Futterkiste");

// Set current property values.
customer.Address = "Obere Str. 57";
customer.City = "Berlin";
customer.PostalCode = "12209";
customer.Country = "Germany";

// Set property values to update.
customer.ContactName = "Peter Franken";
customer.ContactTitle = "Marketing Manager";
customer.Phone = "089-0877310";
customer.Fax = "089-0877451";

try
{
    // Attach the existing customer to the context and mark it as updated.
    context.AttachTo("Customers", customer);
    context.UpdateObject(customer);

    // Send updates to the data service.
    context.SaveChanges();
}
catch (DataServiceClientException ex)
{
    throw new ApplicationException(
        "An error occurred when saving changes.", ex);
}

Vea también

Otros recursos

Biblioteca de cliente de WCF Data Services