Бөлісу құралы:


EntityKey Класс

Определение

Предоставляет устойчивую ссылку на объект, который является экземпляром типа сущности.

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
Атрибуты
Реализации

Примеры

В этих примерах показано, как создать и использовать объект 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 (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);
    }
}

Комментарии

Объекты EntityKey неизменяемы, т. е. после их создания они не могут быть изменены.

Конструкторы

Имя Описание
EntityKey()

Инициализирует новый экземпляр класса EntityKey.

EntityKey(String, IEnumerable<EntityKeyMember>)

Инициализирует новый экземпляр EntityKey класса с именем набора сущностей и IEnumerable<T> коллекцией EntityKeyMember объектов.

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

Инициализирует новый экземпляр EntityKey класса с именем набора сущностей и универсальной KeyValuePair коллекцией.

EntityKey(String, String, Object)

Инициализирует новый экземпляр EntityKey класса с именем набора сущностей и определенной парой ключей сущностей.

Поля

Имя Описание
EntityNotValidKey

Простая EntityKey идентификация сущности, которая привела к сбою операции TREAT .

NoEntitySetKey

Одноэлементное EntityKey определение сущности, доступной только для чтения.

Свойства

Имя Описание
EntityContainerName

Возвращает или задает имя контейнера сущностей.

EntityKeyValues

Возвращает или задает значения ключей, связанные с этим EntityKey.

EntitySetName

Возвращает или задает имя набора сущностей.

IsTemporary

Возвращает значение, указывающее, является ли временным EntityKey .

Методы

Имя Описание
Equals(EntityKey)

Возвращает значение, указывающее, равен ли этот экземпляр указанному EntityKey.

Equals(Object)

Возвращает значение, указывающее, равен ли этот экземпляр указанному объекту.

GetEntitySet(MetadataWorkspace)

Возвращает набор сущностей для этого ключа сущности из заданной рабочей области метаданных.

GetHashCode()

Служит хэш-функцией для текущего EntityKey объекта. GetHashCode() подходит для хэширования алгоритмов и структур данных, таких как хэш-таблица.

GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
OnDeserialized(StreamingContext)

Вспомогательный метод, используемый для десериализации EntityKey.

OnDeserializing(StreamingContext)

Вспомогательный метод, используемый для десериализации EntityKey.

ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Операторы

Имя Описание
Equality(EntityKey, EntityKey)

Сравнивает два объекта EntityKey.

Inequality(EntityKey, EntityKey)

Сравнивает два объекта EntityKey.

Применяется к