Suppose I send a request to the database and receive 1000 objects, if I send this request again using the same DbContext object, then I will receive these objects from the local storage. And if, when processing another request from an asp.net, the application sends the same sql request to the database at the same time or with a small difference (for example, 0.5 seconds), does ef contact the database again?

I have a table that is rarely updated and can fit in RAM without any problems. Is it possible to cache it and update it only, for example, every 24 hours? (I mean by means of the framework, and not a static collection in the service)

    1 answer 1

    Entity Framework does not support such a script. In versions prior to the 6th EF, it slowed down significantly if a lot of objects appeared in DbContext , therefore the standard scenario of working with it is a short lifetime.

    In a web application, it is most convenient to make the lifetime the same as the lifetime of the web request; in this case, all operations performed as part of processing the request are wrapped in a transaction. As a rule, this is exactly what is needed.

    As for caching, the solution to this problem without performance tests is likely to be premature optimization. If the table is small and changes very rarely, the SQL server itself will be fine to cache it. First, it will probably fit in one data page (8Kbytes) and SQL-server will load it in one disk access; secondly, if it is requested regularly, it will simply be in the cache of the SQL server; thirdly, if no one writes to it, there will be no locks.

    If caching is required in the future, it can be added by means of aspect programming : develop caching decorators for repositories. These decorators could check if the data is in the cache. In case of their absence, decorators request data from the database and put it in the cache. With the concept of interceptors, implemented in powerful IoC containers, such decorators can be very simple to design.