Question

I have some code (more complex than in this example) where I don't understand why the FirstOrDefault call, which clearly round-trips to DB, is not returning a fresh entity from 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();

I thought Find will return me the user from the context, if available, but FirstOrDefault always a user with fresh values from database.

Can anyone explain? How would I overcome this effect?

Was it helpful?

Solution

Worth reading this http://msdn.microsoft.com/en-us/data/jj573936,

"When results are returned from the database, objects that do not exist in the context are attached to the context. If an object is already in the context, the existing object is returned (the current and original values of the object's properties in the entry are not overwritten with database values)."

the load and reload methods are worth a read too. Sounds like you want that behaviour.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top