Prevent cached objects to end up in the database with Entity Framework
Posted
by
Dirk Boer
on Stack Overflow
See other posts from Stack Overflow
or by Dirk Boer
Published on 2014-08-15T20:25:33Z
Indexed on
2014/08/18
16:24 UTC
Read the original article
Hit count: 114
We have an ASP.NET project with Entity Framework and SQL Azure.
A big part of our data only needs to be updated a few times a day, other data is very volatile.
- The data that barely changes we cache in memory at startup, detach from the context and than use it mainly for reading, drastically lowering the amount of database requests we have to do.
- The volatile data is requested everytime by a DbContext per Http request.
- When we do an update to the cached data, we send a message to all instances to catch a fresh version of all the data from the SQL server.
So far, so good.
Until we introduced a bug that linked one of these 'cached' objects to the 'volatile' data, and did a SaveChanges.
Well, that was quite a mess.
The whole data tree was added again and again by every update, corrupting the whole database with a whole lot of duplicated data.
As a complete hack I added a completely arbitrary column with a UniqueConstraint and some gibberish data on one of the root tables; hopefully failing the SaveChanges() next time we introduce such a bug because it will violate the Unique Constraint.
But it is of course hacky, and I'm still pretty scared ;P Are there any better ways to prevent whole tree's of cached objects ending up in the database?
More information
- Project is ASP.NET MVC
- I cache this data, because it is mainly read only, and this saves a tons of extra database calls per http request
© Stack Overflow or respective owner