我开始搞乱 EF 4.0 因为我对 POCO 的可能性感到好奇......我想模拟断开连接的 Web 环境并编写了以下代码来模拟这个:
- 在数据库中保存一个测试对象。
- 检索测试对象
- 处理与我用来检索它的测试对象关联的 DataContext
- 更新测试对象
- 创建一个新的数据上下文并持久化测试对象上的更改,这些更改在针对我的 POCO 对象生成的 DynamicProxy 中自动跟踪。
问题是当我在上面的 Test 方法中调用 dataContext.SaveChanges 时,没有应用更新。当我检查它的 EntityStateTracker 时,testStore 实体显示“已修改”状态,但是当我在新的 dataContext 的 Stores 属性中查看它时,它不再被修改。我原以为在新的 dataContext 上调用 Attach 方法也会使对象的“已修改”状态结束,但情况似乎并非如此。有什么我想念的吗?我肯定正在使用 DynamicProxies 与自我跟踪 POCO 合作。
private static void SaveTestStore(string storeName = "TestStore")
{
using (var context = new DataContext())
{
Store newStore = context.Stores.CreateObject();
newStore.Name = storeName;
context.Stores.AddObject(newStore);
context.SaveChanges();
}
}
private static Store GetStore(string storeName = "TestStore")
{
using (var context = new DataContext())
{
return (from store in context.Stores
where store.Name == storeName
select store).SingleOrDefault();
}
}
[Test]
public void Test_Store_Update_Using_Different_DataContext()
{
SaveTestStore();
Store testStore = GetStore();
testStore.Name = "Updated";
using (var dataContext = new DataContext())
{
dataContext.Stores.Attach(testStore);
dataContext.SaveChanges(SaveOptions.DetectChangesBeforeSave);
}
Store updatedStore = GetStore("Updated");
Assert.IsNotNull(updatedStore);
}