我有一些代碼(比這個例子更復雜的),我不明白爲什麼FirstOrDefault通話,這清楚地往返於DB,是不是從數據庫返回一個新的實體:爲什麼EF在FirstOrDefault調用(EF6)後沒有從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
始終是具有來自數據庫的新值的用戶。
任何人都可以解釋一下嗎?我將如何克服這種影響?