POCOの可能性に興味があるので、EF 4.0をいじり始めました...切断されたWeb環境をシミュレートしたいと思い、これをシミュレートするために次のコードを記述しました。
- テストオブジェクトをデータベースに保存します。
- テストオブジェクトを取得します
- 取得に使用したテストオブジェクトに関連付けられたDataContextを破棄します
- テストオブジェクトを更新します
- 新しいデータコンテキストを作成し、POCOオブジェクトに対して生成されたDynamicProxy内で自動的に追跡されるテストオブジェクトの変更を永続化します。
問題は、上記のTestメソッドでdataContext.SaveChangesを呼び出すと、更新が適用されないことです。testStoreエンティティは、EntityStateTrackerを確認すると「変更済み」のステータスを示しますが、新しい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);
}