EntityKey 类

定义

提供对作为实体类型实例的对象的持久引用。Provides a durable reference to an object that is an instance of an entity type.

public ref class EntityKey sealed : IEquatable<System::Data::EntityKey ^>
[System.Runtime.Serialization.DataContract(IsReference=true)]
[System.Serializable]
public sealed class EntityKey : IEquatable<System.Data.EntityKey>
[<System.Runtime.Serialization.DataContract(IsReference=true)>]
[<System.Serializable>]
type EntityKey = class
    interface IEquatable<EntityKey>
Public NotInheritable Class EntityKey
Implements IEquatable(Of EntityKey)
继承
EntityKey
属性
实现

示例

这些示例基于 Microsoft SQL Server 产品示例:数据库These examples are based on the Microsoft SQL Server Product Samples: Database. 示例演示如何创建和使用 EntityKeyThe examples show you how to create and use an 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.");
    }
}
Using context As New AdventureWorksEntities()
    Dim entity As Object = Nothing
    Dim entityKeyValues As IEnumerable(Of KeyValuePair(Of String, Object)) = _
        New KeyValuePair(Of String, Object)() {New KeyValuePair(Of String, Object)("SalesOrderID", 43680)}

    ' Create the key for a specific SalesOrderHeader object. 
    Dim key As New EntityKey("AdventureWorksEntities.SalesOrderHeaders", entityKeyValues)

    ' Get the object from the context or the persisted store by its key. 
    If context.TryGetObjectByKey(key, entity) Then
        Console.WriteLine("The requested " & entity.GetType().FullName & " object was found")
    Else
        Console.WriteLine("An object with this key could not be found.")
    End If
End Using
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        // Create the key that represents the order.
        EntityKey orderKey =
            new EntityKey("AdventureWorksEntities.SalesOrderHeaders",
                "SalesOrderID", orderId);

        // Create the stand-in SalesOrderHeader object
        // based on the specified SalesOrderID.
        SalesOrderHeader order = new SalesOrderHeader();
        order.EntityKey = orderKey;

        // Assign the ID to the SalesOrderID property to matche the key.
        order.SalesOrderID = (int)orderKey.EntityKeyValues[0].Value;

        // Attach the stand-in SalesOrderHeader object.
        context.SalesOrderHeaders.Attach(order);

        // Create a new SalesOrderDetail object.
        // You can use the static CreateObjectName method (the Entity Framework
        // adds this method to the generated entity types) instead of the new operator:
        // SalesOrderDetail.CreateSalesOrderDetail(1, 0, 2, 750, 1, (decimal)2171.2942, 0, 0,
        //                                         Guid.NewGuid(), DateTime.Today));
        SalesOrderDetail detail = new SalesOrderDetail
        {
            SalesOrderID = orderId,
            SalesOrderDetailID = 0,
            OrderQty = 2,
            ProductID = 750,
            SpecialOfferID = 1,
            UnitPrice = (decimal)2171.2942,
            UnitPriceDiscount = 0,
            LineTotal = 0,
            rowguid = Guid.NewGuid(),
            ModifiedDate = DateTime.Now
        };

        order.SalesOrderDetails.Add(detail);

        context.SaveChanges();
    }
    catch (InvalidOperationException)
    {
        Console.WriteLine("Ensure that the key value matches the value of the object's ID property.");
    }
    catch (UpdateException)
    {
        Console.WriteLine("An error has occurred. Ensure that an object with the '{0}' key value exists.",
        orderId);
    }
}
Using context As New AdventureWorksEntities()
    Try
        ' Create the key that represents the order. 
        Dim orderKey As New EntityKey("AdventureWorksEntities.SalesOrderHeaders", "SalesOrderID", orderId)

        ' Create the stand-in SalesOrderHeader object 
        ' based on the specified SalesOrderID. 
        Dim order As New SalesOrderHeader()
        order.EntityKey = orderKey

        ' Assign the ID to the SalesOrderID property to matche the key. 
        order.SalesOrderID = CInt(orderKey.EntityKeyValues(0).Value)

        ' Attach the stand-in SalesOrderHeader object. 
        context.SalesOrderHeaders.Attach(order)

        ' Create a new SalesOrderDetail object. 
        ' You can use the static CreateObjectName method (the Entity Framework 
        ' adds this method to the generated entity types) instead of the new operator: 
        ' SalesOrderDetail.CreateSalesOrderDetail(1, 0, 2, 750, 1, (decimal)2171.2942, 0, 0, 
        ' Guid.NewGuid(), DateTime.Today)); 
        Dim detail = New SalesOrderDetail With
        {
            .SalesOrderID = 0,
            .SalesOrderDetailID = 0,
            .OrderQty = 2,
            .ProductID = 750,
            .SpecialOfferID = 1,
            .UnitPrice = CDec(2171.2942),
            .UnitPriceDiscount = 0,
            .LineTotal = 0,
            .rowguid = Guid.NewGuid(),
            .ModifiedDate = DateTime.Now
        }

        order.SalesOrderDetails.Add(detail)

        context.SaveChanges()
    Catch generatedExceptionName As InvalidOperationException
        Console.WriteLine("Ensure that the key value matches the value of the object's ID property.")
    Catch generatedExceptionName As UpdateException
        Console.WriteLine("An error has occurred. Ensure that an object with the '{0}' key value exists.", orderId)
    End Try
End Using

注解

EntityKey 对象是不可变的,也就是说,这些对象在构造之后不可以修改。The EntityKey objects are immutable; that is, after they are constructed they cannot be modified.

有关详细信息,请参阅使用 实体键For more information, see Working with Entity Keys.

构造函数

EntityKey()

初始化 EntityKey 类的新实例。Initializes a new instance of the EntityKey class.

EntityKey(String, IEnumerable<EntityKeyMember>)

使用实体集名称和 EntityKey 对象的 IEnumerable<T> 集合初始化 EntityKeyMember 类的新实例。Initializes a new instance of the EntityKey class with an entity set name and an IEnumerable<T> collection of EntityKeyMember objects.

EntityKey(String, IEnumerable<KeyValuePair<String,Object>>)

使用实体集名称和泛型 EntityKey 集合初始化 KeyValuePair 类的新实例。Initializes a new instance of the EntityKey class with an entity set name and a generic KeyValuePair collection.

EntityKey(String, String, Object)

使用实体集名称和特定实体键对初始化 EntityKey 类的新实例。Initializes a new instance of the EntityKey class with an entity set name and specific entity key pair.

字段

EntityNotValidKey

一个简单的 EntityKey,标识由失败的 TREAT 运算产生的实体。A simple EntityKey identifying an entity that resulted from a failed TREAT operation.

NoEntitySetKey

一个单独的 EntityKey,它标识一个只读实体。A singleton EntityKey by which a read-only entity is identified.

属性

EntityContainerName

获取或设置实体容器的名称。Gets or sets the name of the entity container.

EntityKeyValues

获取或设置与此 EntityKey 关联的键值。Gets or sets the key values associated with this EntityKey.

EntitySetName

获取或设置实体集的名称。Gets or sets the name of the entity set.

IsTemporary

获取一个值,该值指示 EntityKey 是否是临时的。Gets a value that indicates whether the EntityKey is temporary.

方法

Equals(EntityKey)

返回一个值,该值指示此实例是否与指定的 EntityKey 相等。Returns a value that indicates whether this instance is equal to a specified EntityKey.

Equals(Object)

返回一个值,该值指示此实例是否与指定的对象相等。Returns a value that indicates whether this instance is equal to a specified object.

GetEntitySet(MetadataWorkspace)

从给定的元数据工作区获取此实体键的实体集。Gets the entity set for this entity key from the given metadata workspace.

GetHashCode()

用作当前 EntityKey 对象的哈希函数。Serves as a hash function for the current EntityKey object. GetHashCode() 适用于哈希算法和诸如哈希表之类的数据结构。GetHashCode() is suitable for hashing algorithms and data structures such as a hash table.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
OnDeserialized(StreamingContext)

用于反序列化 EntityKey 的帮助器方法。Helper method that is used to deserialize an EntityKey.

OnDeserializing(StreamingContext)

用于反序列化 EntityKey 的帮助器方法。Helper method that is used to deserialize an EntityKey.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

运算符

Equality(EntityKey, EntityKey)

比较两个 EntityKey 对象。Compares two EntityKey objects.

Inequality(EntityKey, EntityKey)

比较两个 EntityKey 对象。Compares two EntityKey objects.

适用于