Wil*_*lem 5 .net c# entity-framework
可以说,我有一个EntityObject电话someProduct:
//Get the object
Product someProduct = someObjectContext.Product.First();
//At runtime at some point, recreate the ObjectContext
someObjectContext = new SomeObjectContext();
//Try to refresh someProduct on the new ObjectContext
someObjectContext.Refresh(RefreshMode.StoreWins, someProduct);
Run Code Online (Sandbox Code Playgroud)
当第三行执行时,会抛出异常:
要刷新的对象集合中索引 0 处的元素具有 null EntityKey 属性值或未附加到此 ObjectStateManager。
EntityObject这是刷新新创建的正确方法吗ObjectContext?
编辑:
new的原因ObjectContext是为了刷新所有的dirty EntityObjects。
在刷新之前首先将实体附加到上下文,
someObjectContext.Products.Attach(someProduct);
Run Code Online (Sandbox Code Playgroud)
或者
someObjectContext.Set<Product>().Attach(someProduct);
Run Code Online (Sandbox Code Playgroud)
应该可以做到这一点。