Reputation: 5621
If I'm using .Find()
instead of .Where()
to query an object, and someone updates the database making the in memory model out of sync, does Entity know/is Entity alerted to the change so that it updates the model in memory?
Does .Find()
expose me to the risk of missing data?
Upvotes: 0
Views: 51
Reputation: 109292
is Entity alerted to the change so that it updates the model in memory?
No. I've never seen an ORM that does that. It is possible, but not trivial. You can read more about it in Query Notifications in SQL Server. And that's not even the whole story because once you can listen to database events you'd heave to decide what to do with them client-side. Like, what to do with changed values that were also changed in the client?
But the Find
method is designed to do almost the opposite. It always tries to return an object from the local cache. It only queries the database if the object isn't there yet. So it's designed to return stale data, if you like. It is perfect for relatively complex operations in which you're going to need an object multiple times, but don't want to get it from the database all the time.
LINQ query statements (Find
isn't LINQ) are somewhere in the middle. They do query the database, but they don't update objects that are in the cache already. If you changed an object locally, the changes won't be erased by a Select
statement.
You can refresh the local cache, but the DbContext
API, which was an improvement of the former ObjectContext
API, even makes that a bit less easy than before. The message is: don't do it. If you want fresh data: create a new context.
Upvotes: 1
Reputation: 152644
Does
.Find()
expose me to the risk of missing data?
Sure, but so does First()
and Where()
. Any time you load data into memory you risk the data behind it changing without your knowledge. You can minimize that risk in EF by not hanging on to entities for long periods of time, and using a new context for every DB operation (or operations).
Upvotes: 0