EntityKey 类表示实体对象的键。 可以使用类构造函数创建 EntityKey 的一个实例,也可以使用 ObjectContext 的静态 CreateEntityKey 方法,以生成某个特定对象的 EntityKey。 使用实体键附加对象或从数据源返回特定对象。 有关更多信息,请参见使用实体键(实体框架)。
本主题中的示例基于 Adventure Works 销售模型。 若要运行本示例中的代码,必须已将 AdventureWorks 销售模型添加到您的项目中,并将项目配置为使用实体框架 。 为此,请完成如何:手动配置实体框架项目和如何:手动定义模型和映射文件(实体框架)中的过程。
示例
下面的示例使用指定的键/值对以及限定的实体集名称创建 EntityKey 的一个实例。 然后使用此键检索该对象本身。
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())
{
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.");
}
}
对于独立的关联,使用下面示例中所述的方法定义关系。 对于外键关联,通过设置依赖对象的外键属性的值来定义关系。 有关更多信息,请参见定义和管理关系(实体框架)。
下面的示例使用指定的键名称、键值以及限定的实体集名称创建 EntityKey 的一个实例。 然后使用此键附加对象以及定义关系。
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 occured. Ensure that an object with the '{0}' key value exists.", orderId)
End Try
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 occured. Ensure that an object with the '{0}' key value exists.",
orderId);
}
}
下面的示例使用已分离对象中的键值创建 EntityKey 的一个实例。 然后使用此键检索该对象的附加实例。
Private Shared Sub ApplyItemUpdates(ByVal updatedItem As SalesOrderDetail)
' Define an ObjectStateEntry and EntityKey for the current object.
Dim key As EntityKey
Dim originalItem As Object
Using context As 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, originalItem) Then
' Call the ApplyCurrentValues method to apply changes
' from the updated item to the original version.
context.ApplyCurrentValues(key.EntitySetName, updatedItem)
End If
context.SaveChanges()
End Using
End Sub
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();
}
}