This documentation is archived and is not being maintained.

ObjectContext.DeleteObject Method

Marks an object for deletion.

Namespace:  System.Data.Objects
Assembly:  System.Data.Entity (in System.Data.Entity.dll)

public void DeleteObject(
	Object entity


Type: System.Object

An object that specifies the entity to delete. The object can be in any state except Detached.

Marks an object for deletion from the ObjectStateManager. The object is deleted in the data source when the SaveChanges method is called.

Deleting the parent object also deletes all the child objects in the constrained relationship. This result is the same as enabling the CascadeDelete property on the association for the relationship. The DeleteObject method can be called on entities that are already deleted.

These examples are based on the Adventure Works Sales Model.

This example constructs an EntityKey with a specific ProductID, uses the key to retrieve a Product object from the data source, deletes the product, and saves the changes to the database.

This example deletes an existing order item, adds a new item, and saves the changes to the database.

// Specify the order to update. 
int orderId = 43680;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
        SalesOrderHeader order =
            ("it.SalesOrderID = @id", new ObjectParameter(
             "id", orderId)).First();

        // Change the status and ship date of an existing order.
        order.Status = 1;
        order.ShipDate = DateTime.Today;

        // Load items for the order, if not already loaded. 
        if (!order.SalesOrderDetail.IsLoaded)

        // Delete the first item in the order.

        // Create a new item using the static Create method  
        // and add it to the order.
            0, 2, 750, 1, (decimal)2171.2942, 0, 0,
            Guid.NewGuid(), DateTime.Today));

        // Save changes in the object context to the database. 
        int changes = context.SaveChanges();

        Console.WriteLine(changes.ToString() + " changes saved!");
        Console.WriteLine("Updated item for order: "
            + order.SalesOrderID.ToString());

        foreach (SalesOrderDetail item in order.SalesOrderDetail)
            Console.WriteLine("Item ID: "
                + item.SalesOrderDetailID.ToString() + "  Product: "
                + item.ProductID.ToString() + "  Quantity: "
                + item.OrderQty.ToString());
    catch (UpdateException ex)

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5 SP1