通过


ObjectContext.TryGetObjectByKey(EntityKey, Object) 方法

定义

返回具有指定实体键的对象。

public:
 bool TryGetObjectByKey(System::Data::EntityKey ^ key, [Runtime::InteropServices::Out] System::Object ^ % value);
public bool TryGetObjectByKey(System.Data.EntityKey key, out object value);
member this.TryGetObjectByKey : System.Data.EntityKey * obj -> bool
Public Function TryGetObjectByKey (key As EntityKey, ByRef value As Object) As Boolean

参数

key
EntityKey

要找到的对象键。

value
Object

此方法返回时,包含对象。

返回

如果已成功检索对象,则为 false 如果为 key 临时连接,则 nullvalue 或为 null

例外

key元数据不兼容。

keynull

示例

此示例为给定类型的实体创建一个 EntityKey 实体,然后尝试按键检索实体。

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    Object entity = null;
    IEnumerable<KeyValuePair<string, object>> entityKeyValues =
        new KeyValuePair<string, object>[] {
            new KeyValuePair<string, object>("SalesOrderID", 43680) };

    // Create the  key for a specific SalesOrderHeader object.
    EntityKey key = new EntityKey("AdventureWorksEntities.SalesOrderHeaders", entityKeyValues);

    // Get the object from the context or the persisted store by its key.
    if (context.TryGetObjectByKey(key, out entity))
    {
        Console.WriteLine("The requested " + entity.GetType().FullName +
            " object was found");
    }
    else
    {
        Console.WriteLine("An object with this key " +
            "could not be found.");
    }
}

注解

TryGetObjectByKey 尝试检索具有指定 EntityKey 对象 ObjectStateManager的对象。 如果对象当前未加载到对象上下文中,则尝试从数据源返回对象时执行查询。

TryGetObjectByKey使用该方法避免在找不到对象时处理ObjectNotFoundException引发GetObjectByKey的对象。

此方法将返回处于 Deleted 状态的对象。

临时键不能用于从数据源返回对象。

TryGetObjectByKey 方法应用 GetObjectByKey 方法的标准 .NET TryParse 模式,在捕获 ObjectNotFoundException 时返回 false

适用于

另请参阅