1
我需要將EF對象(以前分離)附加到新的ObjectContext。問題是我不知道它之前是否附加或加載過。如果有一個對象使用相同的密鑰加載到ObjectContext,那麼當我嘗試附加時,會出現異常。有沒有辦法檢查是否有一個已經連接了特定密鑰的對象?如何檢查對象是否附加到ObjectContext?
謝謝!
我需要將EF對象(以前分離)附加到新的ObjectContext。問題是我不知道它之前是否附加或加載過。如果有一個對象使用相同的密鑰加載到ObjectContext,那麼當我嘗試附加時,會出現異常。有沒有辦法檢查是否有一個已經連接了特定密鑰的對象?如何檢查對象是否附加到ObjectContext?
謝謝!
對象上下文中的對象狀態由ObjectStateManager管理。
從MSDN:
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");
}
}
另見:http://msdn.microsoft.com/en-us/library/dd456854.aspx
從以前的MSDN鏈接:
// The changes are tracked as they occur and the state of the object is Modified.
Console.WriteLine(context.ObjectStateManager.GetObjectStateEntry(newItem).State);
..我想你的情況,這可能是一個的緩存項目。
希望它有幫助!
是的,我有同樣的想法,現在檢查它是否會與POCO對象一起工作。 – ElDog
請參閱:http://msdn.microsoft.com/en-us/library/dd456854.aspx – maxbeaudoin