ObjectStateManager 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
維護實體類型實例與關聯實例的物件狀態與身份管理。
public ref class ObjectStateManager
public class ObjectStateManager
type ObjectStateManager = class
Public Class ObjectStateManager
- 繼承
-
ObjectStateManager
範例
以下範例從 ObjectContext 取得 ,ObjectStateManager並使用狀態管理器存取上下文中的物件。
int orderId = 43680;
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
ObjectStateManager objectStateManager = context.ObjectStateManager;
ObjectStateEntry stateEntry = null;
var order = (from o in context.SalesOrderHeaders
where o.SalesOrderID == orderId
select o).First();
// Attempts to retrieve ObjectStateEntry for the given EntityKey.
bool isPresent = objectStateManager.TryGetObjectStateEntry(((IEntityWithKey)order).EntityKey, out stateEntry);
if (isPresent)
{
Console.WriteLine("The entity was found");
}
}
以下範例使用 TryGetObjectStateEntry(EntityKey, ObjectStateEntry) 了 返回 上 ObjectStateManager 的方法,根據其實體鍵數取得物件。
private static void ApplyItemUpdates(SalesOrderDetail originalItem,
SalesOrderDetail updatedItem)
{
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
context.SalesOrderDetails.Attach(updatedItem);
// Check if the ID is 0, if it is the item is new.
// In this case we need to chage the state to Added.
if (updatedItem.SalesOrderDetailID == 0)
{
// Because the ID is generated by the database we do not need to
// set updatedItem.SalesOrderDetailID.
context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added);
}
else
{
// If the SalesOrderDetailID is not 0, then the item is not new
// and needs to be updated. Because we already added the
// updated object to the context we need to apply the original values.
// If we attached originalItem to the context
// we would need to apply the current values:
// context.ApplyCurrentValues("SalesOrderDetails", updatedItem);
// Applying current or original values, changes the state
// of the attached object to Modified.
context.ApplyOriginalValues("SalesOrderDetails", originalItem);
}
context.SaveChanges();
}
}
備註
ObjectStateManager 追蹤查詢結果,並提供合併多個重疊查詢結果的邏輯。 當使用者插入、刪除或修改物件時,它還能執行記憶體內的變更追蹤,並提供更新的變更集。 變更集被變更處理器用來持久化修改。
此類別通常用於 ObjectContext 應用,而非直接應用。
建構函式
| 名稱 | Description |
|---|---|
| ObjectStateManager(MetadataWorkspace) |
初始化 ObjectStateManager 類別的新執行個體。 |
屬性
| 名稱 | Description |
|---|---|
| MetadataWorkspace |
他會和 MetadataWorkspace 這個州經理有關聯。 |
方法
事件
| 名稱 | Description |
|---|---|
| ObjectStateManagerChanged |
當實體被加入或移除狀態管理者時,會發生這種情況。 |