我有一些代码(比这个例子更复杂),我不明白为什么FirstOrDefault调用(显然是往返DB)没有从DB返回一个新实体:
var dbContext = new MyDBContext();
// this will not round-trip to Db if found in context
var user = this.dbContext.EFUsers.Find(someUID);
// some other work here with 'user'
this.dbContext.ObjectContext.Detach(user);
// stuff in disconnected mode
var newUser = new EFUser() { UID = someUID };
// stuff in disconnected mode
this.dbContext.EFUsers.Attach(newUser);
// finish working with newUser
// (eg. deletion of many-to-many relation to avoid loading related entities in memory)
user = this.dbContext.EFUsers.FirstOrDefault(us => us.UID == someUID);
// I would expect at this point that 'user' will be queried with fresh values from DB,
// In reality, I get back only the entity with UID filled in, 'newUser' from above
// some update user goes here which fails because of the above
dbContext.SaveChanges();
我认为Find
会将用户从上下文中返回给我(如果可用),但FirstOrDefault
始终是具有数据库新值的用户。
有人可以解释一下吗?我该如何克服这种影响?
答案 0 :(得分:3)
值得一读 http://msdn.microsoft.com/en-us/data/jj573936 ,
“从数据库返回结果时,不返回结果 在上下文中存在附加到上下文。如果一个对象是 已经在上下文中,返回现有对象(当前 并且条目中对象属性的原始值不是 用数据库值覆盖)。“
加载和重载方法也值得一读。 听起来你想要这种行为。
http://msdn.microsoft.com/en-us/data/jj592911.aspx
http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbentityentry.reload(v=vs.113).aspx