通过


ObjectContext.CreateEntityKey(String, Object) 方法

定义

为特定对象创建实体键,或返回实体键(如果已存在)。

public:
 System::Data::EntityKey ^ CreateEntityKey(System::String ^ entitySetName, System::Object ^ entity);
public System.Data.EntityKey CreateEntityKey(string entitySetName, object entity);
member this.CreateEntityKey : string * obj -> System.Data.EntityKey
Public Function CreateEntityKey (entitySetName As String, entity As Object) As EntityKey

参数

entitySetName
String

实体对象所属的实体集的完全限定名称。

entity
Object

要为其检索实体键的对象。

返回

对象的 EntityKey 对象。

例外

当任一参数为 null.

何时 entitySetName 为空。

-或-

当实体集中不存在对象的类型 entity 时。

-或-

entitySetName未完全限定时。

无法根据提供的参数成功构造实体键时。

示例

在此示例中, CreateEntityKey 用于检索现有对象的实体键。

private static void ApplyItemUpdates(SalesOrderDetail updatedItem)
{
    // Define an ObjectStateEntry and EntityKey for the current object.
    EntityKey key = default(EntityKey);
    object originalItem = null;

    using (AdventureWorksEntities context = new AdventureWorksEntities())
    {
        // Create the detached object's entity key.
        key = context.CreateEntityKey("SalesOrderDetails", updatedItem);

        // Get the original item based on the entity key from the context
        // or from the database.
        if (context.TryGetObjectByKey(key, out originalItem))
        {
            // Call the ApplyCurrentValues method to apply changes
            // from the updated item to the original version.
            context.ApplyCurrentValues(key.EntitySetName, updatedItem);
        }

        context.SaveChanges();
    }
}

注解

如果不存在此方法EntityKeyentity,该方法CreateEntityKey将为它创建一个新键。

此方法用于确定已 EntityKey 附加到 ObjectContext同一对象的对象。 如果附加了具有相同对象 EntityKey ,则会引发异常。 CreateEntityKey在调用Attach该方法之前,使用该方法尝试检索EntityKey分离的对象。

适用于