Reputation: 1
Question about scaling ASP.NET & EF Core scaling horizontally. My understanding is that each EF core application maintains its own cache. So if I have a single EF entity in my application, and I want to have multiple ASP.NET application instances, is there a common way to ensure that the EF cache (for this single entity) can stay synchronized across the application instances?
I see that there is https://github.com/VahidN/EFCoreSecondLevelCacheInterceptor It says that this project can use Redis, acting as distributed cache.
This project mentions that its suggested use case is "global site settings and public data, such as infrequently changing articles or comments". My use case is frequently-changing data entities with CRUD.
Upvotes: 0
Views: 196
Reputation: 488
Entity Framework holds its internal state in DbContext
. That state is NOT used as cache. It's only there to detect if something was changed between creation of the DbContext
and execution of SaveChanges
There is no synchronization. DbContext will use it to calculate what query to send and send it inside an SQL transaction. Transactions ensure data consistency. They employ Optimistic Concurrency, so if you SELECT some data out, and try to UPDATE same rows back, but another transaction just overwrote the data that you previously SELECTed the transaction will fail. Failing transaction changes nothing in the database. Also after such failed transaction DbContext
will NOT be updated so it's completely pointless to keep it alive. This approach works great with this one assumption:
You should Dispose
(that also "cleans the cache") the DbContext
as soon as possible, and modern C# syntax does this perfectly.
// Code of current method
using (var context = new AppDbContext())
{
var firstProduct = context.Products.FirstOrDefault();
if (firstProduct != null)
{
// Update the price of the first product
firstProduct.Price = 9.99m;
// Save the changes to the database
context.SaveChanges();
}
// Other code of current method
Creation of DbContext
itself is really fast. The slow part is establishing the connection with SQL Server. This is easily optimized with connection pooling. A single line in Program.cs
is enough to turn it on.
services.AddDbContext<EmployeeContext>(options => options.UseSqlServer(connection));
The most of the caching is done on the SQL Server part.
EF Core and SqlServer work perfectly together. It's just like they both were made by the same company ^_^
Upvotes: 0