This documentation is archived and is not being maintained.

ObjectContext.ObjectStateManager Property

Gets the object state manager used by the object context to track object changes.

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

public ObjectStateManager ObjectStateManager { get; }

These examples are based on the Adventure Works Sales Model. This example gets the ObjectStateManager from the ObjectContext and uses the state manager to access an object in the context.

int orderId = 43680;

using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    try
    {
        ObjectStateManager objectStateManager = advWorksContext.ObjectStateManager;
        ObjectStateEntry stateEntry = null;

        SalesOrderHeader order =
            advWorksContext.SalesOrderHeader.Where
            ("it.SalesOrderID = @id", new ObjectParameter(
             "id", orderId)).First();

        // Attempts to retrieve ObjectStateEntry for the given EntityKey. 
        bool isPresent = objectStateManager.TryGetObjectStateEntry(((IEntityWithKey)order).EntityKey, out stateEntry);
        if (isPresent)
        {
            Console.WriteLine("The entity was found");
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    catch (EntityCommandExecutionException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

This example uses the TryGetObjectStateEntry method on the returned ObjectStateManager to get an object based on its entity key.

private static void ApplyItemUpdates(SalesOrderDetail originalItem,
    SalesOrderDetail updatedItem)
{
    using (AdventureWorksEntities advWorksContext = 
        new AdventureWorksEntities())
    {
        try
        {
            // Attach the original item to the object context.
            advWorksContext.Attach(originalItem);

            // Call the ApplyPropertyChanges method to apply changes 
            // from the updated item to the original version.
            advWorksContext.ApplyPropertyChanges("SalesOrderDetail",
                updatedItem);

            advWorksContext.SaveChanges();
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

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
Show: