我认为调用 ObjectContext.CreateObject() 为 T 创建了一个代理包装器,然后开始使用代理包装器支持的更改通知来跟踪更改。如果是这样,那么为什么我不能将它从上下文中分离出来?
这是我的问题:
public void FailedTest() {
POCOtype fail = context.CreateObject<POCOtype>();
context.Detach(fail); // Throws InvalidOperationException
// "The object cannot be detached because it is not attached to the ObjectStateManager."
}
public void WorkingTest() {
POCOtype happy = context.CreateObject<POCOtype>();
context.AttachTo("POCOtypes", happy);
context.Detach(happy);
// Everything is good.
}
public void VeryOdd_WorkingTest() {
POCOtype odd = context.CreateObject<POCOtype>();
try {
context.Detach(odd); // Throws InvalidOperationException
// "The object cannot be detached because it is not attached to the ObjectStateManager."
} catch(Exception e) { }
context.SaveChanges(); // The object is inserted into the DB.
}
最佳答案
CreateObject
不会创建附加实体。您必须自己手动将实体附加或添加到上下文中。您甚至可以将其附加到其他上下文实例。您的最后一个测试不应插入该实体。我自己测试了一下,并没有插入任何东西。使用新的上下文实例进行测试,或在调用 CreateObject
之前检查 context.ObjectStateManager.GetObjectStateEntries(EntityState.Added)
是否返回任何条目。
关于entity-framework-4 - Entity Framework 中的 T CreateObject<T> 是否也会在创建代理后跟踪更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5955056/