entity-framework-4 - Entity Framework 中的 T CreateObject<T> 是否也会在创建代理后跟踪更改?

标签 entity-framework-4

我认为调用 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/

相关文章:

c# - 如何修改edmx的默认代码生成策略?

wpf - 表/ View 没有定义主键

c# - 坚持 linq 查询

Linq to entity - 从查询中调用用户定义的方法

entity-framework - 组织 EF4 数据层?

sql - 在EF 4.1中DbContext如何跟踪生成的SQL

c# - 如何应用 Skip and Take on Include

.net - 在 Model First 方法中使用时间戳属性进行 EF 并发处理

mysql - 使用 Entity Framework 在表中插入具有最小 mysql 值的日期时间

sql - Entity Framework EF 代码首先使用 ExecuteStoreCommand 执行 sproc 很慢