我看到很多人都在问一个类似的问题,但不是这个问题.我正在尝试用POCO代理做我希望相对简单的事情.
using (var context = new MyObjectContext())
{
context.ContextOptions.ProxyCreationEnabled = true;
// this does indeed create an instance of a proxy for me...
// something like Product_SomeBunchOfNumbersForProxy
var newEntity = context.CreateObject<MyEntity>();
// throws exception because newEntity is not in ObjectStateManager...why??
context.ObjectStateManager.GetObjectStateEntry(newEntity);
// ok, well I guess let's add it to the context manually...
context.AddObject("Model.Products", newEntity);
// doesn't throw an exception...I guess that's good
var state = context.ObjectStateManager.GetObjectStateEntry(newEntity);
// prints System.Data.EntityState.Unchanged...oh...well that's not good
Console.WriteLine(state.State);
// let's try this...
context.DetectChanges();
// doesn't throw an exception...I guess that's good
state = context.ObjectStateManager.GetObjectStateEntry(newEntity);
// prints System.Data.EntityState.Unchanged...still no good...
Console.WriteLine(state.State);
// dunno, worth a shot...
context.Refresh(RefreshMode.ClientWins);
// throws exception because newEntity is not in ObjectStateManager...
// that didn't help...
state = context.ObjectStateManager.GetObjectStateEntry(newEntity);
}
我究竟做错了什么?谢谢!
最佳答案 我没有对代理做太多,但看起来你期望它跟踪一个没有持久状态的对象的变化.
CreateEntity实际上只是创建了对象.这与说“新MyEntity”没什么不同.因此,您必须将该实体添加到上下文并保存更改,然后才能跟踪以下任何真正的“状态”:
using (var context = new MyObjectContext())
{
context.ContextOptions.ProxyCreationEnabled = true;
var newEntity = context.CreateObject<MyEntity>();
context.Add(newEntity);
context.SaveChanges();
// now GetObjectStateEntry(newEntity) should work just fine.
// ...
}