HOW TO:建立 EntityKey (Entity Framework)
EntityKey 類別表示實體物件的索引鍵。 您可以使用類別建構函式建立 EntityKey 的執行個體,或使用 ObjectContext 的靜態 CreateEntityKey 方法為特定物件產生 EntityKey。 實體索引鍵可用來附加物件或從資料來源傳回特定物件。 如需詳細資訊,請參閱使用實體索引鍵 (Entity Framework)。
本主題的範例是根據 Adventure Works Sales Model。 若要執行此範例中的程式碼,您必須已經將 AdventureWorks Sales Model 加入到專案中,並設定您的專案使用 Entity Framework 。 若要這樣做,請完成 HOW TO:手動設定 Entity Framework 專案和 HOW TO:手動定義模型和對應檔 (Entity Framework) 中的程序。
範例
下列範例會使用指定的索引鍵/值組和限定的實體集名稱建立 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();
}
}
另請參閱
工作
HOW TO:使用特定物件的索引鍵傳回此物件 (Entity Framework)