How to: Add, Modify, and Delete Entities (WCF Data Services)

With the WCF Data Services client libraries, you can create, update, and delete entity data in a data service by performing equivalent actions on objects in the DataServiceContext. For more information, see Updating the Data Service (WCF Data Services).

The example in this topic uses the Northwind sample data service and autogenerated client data service classes. This service and the client data classes are created when you complete the WCF Data Services quickstart.

Example

The following example creates a new object instance and then calls the AddObject method on the DataServiceContext to create the item in the context. An HTTP POST message is sent to the data service when the SaveChanges method is called.

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

' Create the new product.
Dim newProduct = _
    Product.CreateProduct(0, "White Tea - loose", False)

' Set property values.
newProduct.QuantityPerUnit = "120gm bags"
newProduct.ReorderLevel = 5
newProduct.UnitPrice = 5.2D

Try
    ' Add the new product to the Products entity set.
    context.AddToProducts(newProduct)

    ' Send the insert to the data service.
    context.SaveChanges()

    Console.WriteLine("New product added with ID {0}.", newProduct.ProductID)
Catch ex As DataServiceRequestException
    Throw New ApplicationException( _
            "An error occurred when saving changes.", ex)
// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

// Create the new product.
Product newProduct =
    Product.CreateProduct(0, "White Tea - loose", false);

// Set property values.
newProduct.QuantityPerUnit = "120gm bags";
newProduct.ReorderLevel = 5;
newProduct.UnitPrice = 5.2M;

try
{
    // Add the new product to the Products entity set.
    context.AddToProducts(newProduct);

    // Send the insert to the data service.
    DataServiceResponse response = context.SaveChanges();

    // Enumerate the returned responses.
    foreach (ChangeOperationResponse change in response)
    {
        // Get the descriptor for the entity.
        EntityDescriptor descriptor = change.Descriptor as EntityDescriptor;

        if (descriptor != null)
        {
            Product addedProduct = descriptor.Entity as Product;

            if (addedProduct != null)
            {
                Console.WriteLine("New product added with ID {0}.",
                    addedProduct.ProductID);
            }
        }
    }
}
catch (DataServiceRequestException ex)
{
    throw new ApplicationException(
        "An error occurred when saving changes.", ex);
}

The following example retrieves and modifies an existing object and then calls the UpdateObject method on the DataServiceContext to mark the item in the context as updated. An HTTP MERGE message is sent to the data service when the SaveChanges method is called.

Dim customerId = "ALFKI"

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

' Get a customer to modify using the supplied ID.
Dim customerToChange = (From customer In context.Customers _
                        Where customer.CustomerID = customerId _
                        Select customer).Single()

' Change some property values.
customerToChange.CompanyName = "Alfreds Futterkiste"
customerToChange.ContactName = "Maria Anders"
customerToChange.ContactTitle = "Sales Representative"

Try
    ' Mark the customer as updated.
    context.UpdateObject(customerToChange)

    ' Send the update to the data service.
    context.SaveChanges()
Catch ex As DataServiceRequestException
    Throw New ApplicationException( _
            "An error occurred when saving changes.", ex)
End Try
string customerId = "ALFKI";

// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

// Get a customer to modify using the supplied ID.
var customerToChange = (from customer in context.Customers
                        where customer.CustomerID == customerId
                        select customer).Single();
 
// Change some property values.
customerToChange.CompanyName = "Alfreds Futterkiste";
customerToChange.ContactName = "Maria Anders";
customerToChange.ContactTitle = "Sales Representative";

try
{
    // Mark the customer as updated.
    context.UpdateObject(customerToChange);

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

The following example calls the DeleteObject method on the DataServiceContext to mark the item in the context as deleted. An HTTP DELETE message is sent to the data service when the SaveChanges method is called.

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

Try
    ' Get the product to delete, by product ID.
    Dim deletedProduct = (From product In context.Products _
                          Where product.ProductID = productID _
                          Select product).Single()


    ' Mark the product for deletion.    
    context.DeleteObject(deletedProduct)

    ' Send the delete to the data service.
    context.SaveChanges()

    ' Handle the error that occurs when the delete operation fails,
    ' which can happen when there are entities with existing 
    ' relationships to the product being deleted.
Catch ex As DataServiceRequestException
    Throw New ApplicationException( _
            "An error occurred when saving changes.", ex)
End Try
// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

try
{
    // Get the product to delete, by product ID.
    var deletedProduct = (from product in context.Products
                          where product.ProductID == productID
                          select product).Single();

    // Mark the product for deletion.    
    context.DeleteObject(deletedProduct);

    // Send the delete to the data service.
    context.SaveChanges();
}
// Handle the error that occurs when the delete operation fails,
// which can happen when there are entities with existing 
// relationships to the product being deleted.
catch (DataServiceRequestException ex)
{
    throw new ApplicationException(
        "An error occurred when saving changes.", ex);
}

The following example creates a new object instance and then calls the AddRelatedObject method on the DataServiceContext to create the item in the context along with the link to the related order. An HTTP POST message is sent to the data service when the SaveChanges method is called.

Dim productId = 25
Dim customerId = "ALFKI"

Dim newItem As Order_Detail = Nothing

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

Try
    ' Get the specific product.
    Dim selectedProduct = (From product In context.Products _
                           Where product.ProductID = productId _
                           Select product).Single()

    ' Get the specific customer.
    Dim cust = (From customer In context.Customers.Expand("Orders") _
                Where customer.CustomerID = customerId _
                Select customer).Single()

    ' Get the first order. 
    Dim order = cust.Orders.FirstOrDefault()

    ' Create a new order detail for the specific product.
    newItem = Order_Detail.CreateOrder_Detail( _
            order.OrderID, selectedProduct.ProductID, 10, 5, 0)

    ' Add the new item with a link to the related order.
    context.AddRelatedObject(order, "Order_Details", newItem)

    ' Add the new order detail to the collection, and
    ' set the reference to the product.
    order.Order_Details.Add(newItem)
    newItem.Order = order
    newItem.Product = selectedProduct

    ' Send the changes to the data service.
    Dim response As DataServiceResponse = context.SaveChanges()

    ' Enumerate the returned responses.
    For Each change As ChangeOperationResponse In response
        ' Get the descriptor for the entity.
        Dim descriptor = TryCast(change.Descriptor, EntityDescriptor)

        If Not descriptor Is Nothing Then
            If TypeOf descriptor.Entity Is Order_Detail Then
                Dim addedItem = TryCast(descriptor.Entity, Order_Detail)

                If Not addedItem Is Nothing Then
                    Console.WriteLine("New {0} item added to order {1}.", _
                        addedItem.Product.ProductName, addedItem.OrderID.ToString())
                End If
            End If
        End If
    Next
Catch ex As DataServiceQueryException
    Throw New ApplicationException( _
            "An error occurred when saving changes.", ex)

    ' Handle any errors that may occur during insert, such as 
    ' a constraint violation.
Catch ex As DataServiceRequestException
    Throw New ApplicationException( _
            "An error occurred when saving changes.", ex)
int productId = 25;
string customerId = "ALFKI";

Order_Detail newItem = null;

// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

try
{
    // Get the specific product.
    var selectedProduct = (from product in context.Products
                           where product.ProductID == productId
                           select product).Single();

    // Get the specific customer.
    var cust = (from customer in context.Customers.Expand("Orders")
                where customer.CustomerID == customerId
                select customer).Single();

    // Get the first order. 
    Order order = cust.Orders.FirstOrDefault();

    // Create a new order detail for the specific product.
    newItem = Order_Detail.CreateOrder_Detail(
        order.OrderID, selectedProduct.ProductID, 10, 5, 0);

    // Add the new item with a link to the related order.
    context.AddRelatedObject(order, "Order_Details", newItem);

    // Add the new order detail to the collection, and
    // set the reference to the product.
    order.Order_Details.Add(newItem);
    newItem.Order = order;
    newItem.Product = selectedProduct;
   
    // Send the changes to the data service.
    DataServiceResponse response = context.SaveChanges();

    // Enumerate the returned responses.
    foreach (ChangeOperationResponse change in response)
    {
        // Get the descriptor for the entity.
        EntityDescriptor descriptor = change.Descriptor as EntityDescriptor;

        if (descriptor != null)
        {
            if (descriptor.Entity.GetType() == typeof(Order_Detail))
            {
                Order_Detail addedItem = descriptor.Entity as Order_Detail;

                if (addedItem != null)
                {
                    Console.WriteLine("New {0} item added to order {1}.", 
                        addedItem.Product.ProductName, addedItem.OrderID.ToString());
                }
            }
        }
    }
}
catch (DataServiceQueryException ex)
{
    throw new ApplicationException(
        "An error occurred when saving changes.", ex);
}

// Handle any errors that may occur during insert, such as 
// a constraint violation.
catch (DataServiceRequestException ex)
{
    throw new ApplicationException(
        "An error occurred when saving changes.", ex);
}

See Also

Tasks

How to: Attach an Existing Entity to the DataServiceContext (WCF Data Services)
How to: Define Entity Relationships (WCF Data Services)

Concepts

Batching Operations (WCF Data Services)

Other Resources

WCF Data Services Client Library