我需要将EF对象(先前已分离)附加到新的ObjectContext。问题是我不知道它之前是否附加或加载过。如果有一个对象加载到ObjectContext,我尝试附加时会出现异常。有没有办法检查是否有一个已附加特定键的对象?
谢谢!
答案 0 :(得分:4)
对象上下文中的对象状态由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);
..我认为在你的情况下,这可能是缓存项目之一。
希望它有所帮助!