【发布时间】:2011-11-29 22:26:48
【问题描述】:
我需要将 EF 对象(之前已分离)附加到新的 ObjectContext。问题是我不知道它之前是附加的还是加载的。如果有一个具有相同键的对象加载到 ObjectContext 我尝试附加时会出现异常。有没有办法检查是否存在已附加特定键的对象?
谢谢!
【问题讨论】:
标签: .net entity-framework
我需要将 EF 对象(之前已分离)附加到新的 ObjectContext。问题是我不知道它之前是附加的还是加载的。如果有一个具有相同键的对象加载到 ObjectContext 我尝试附加时会出现异常。有没有办法检查是否存在已附加特定键的对象?
谢谢!
【问题讨论】:
标签: .net entity-framework
对象上下文中的对象状态由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);
.. 我想在您的情况下,这可能是缓存项目之一。
希望对你有帮助!
【讨论】: