【问题标题】:How to check if an object is attached to ObjectContext?如何检查对象是否附加到 ObjectContext?
【发布时间】:2011-11-29 22:26:48
【问题描述】:

我需要将 EF 对象(之前已分离)附加到新的 ObjectContext。问题是我不知道它之前是附加的还是加载的。如果有一个具有相同键的对象加载到 ObjectContext 我尝试附加时会出现异常。有没有办法检查是否存在已附加特定键的对象?

谢谢!

【问题讨论】:

    标签: .net entity-framework


    【解决方案1】:

    对象上下文中的对象状态由ObjectStateManager 管理。

    来自 MSDN:

    int orderId = 43680;
    
    using (AdventureWorksEntities context =
        new AdventureWorksEntities())
    {
        ObjectStateManager objectStateManager = context.ObjectStateManager;
        ObjectStateEntry stateEntry = null;
    
        var order = (from o in context.SalesOrderHeaders
                     where o.SalesOrderID == orderId
                     select o).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");
        }
    }
    

    另见:http://msdn.microsoft.com/en-us/library/dd456854.aspx

    来自之前的 MSDN 链接:

    // The changes are tracked as they occur and the state of the object is Modified.
    Console.WriteLine(context.ObjectStateManager.GetObjectStateEntry(newItem).State);
    

    .. 我想在您的情况下,这可能是缓存项目之一。

    希望对你有帮助!

    【讨论】:

    • 是的,我也有同样的想法,现在检查它是否适用于 POCO 对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    相关资源
    最近更新 更多