All Projects → VahidN → Efsecondlevelcache.core

VahidN / Efsecondlevelcache.core

Licence: apache-2.0
Entity Framework Core Second Level Caching Library

Projects that are alternatives of or similar to Efsecondlevelcache.core

Dntidentity
A highly customized sample of the ASP.NET Core Identity
Stars: ✭ 145 (-51.67%)
Mutual labels:  entity-framework, entity-framework-core, aspnetcore
Onion Architecture Asp.net Core
WhiteApp API solution template which is built on Onion Architecture with all essential feature using .NET 5!
Stars: ✭ 196 (-34.67%)
Mutual labels:  entity-framework, entity-framework-core, aspnetcore
Efcoresecondlevelcacheinterceptor
EF Core Second Level Cache Interceptor
Stars: ✭ 227 (-24.33%)
Mutual labels:  entity-framework, entity-framework-core, aspnetcore
Gridify
Easy and optimized way to apply Filtering, Sorting, and Pagination using text-based data.
Stars: ✭ 372 (+24%)
Mutual labels:  entity-framework, entity-framework-core
EntityFrameworkCore.Triggered
Triggers for EFCore. Respond to changes in your DbContext before and after they are committed to the database.
Stars: ✭ 361 (+20.33%)
Mutual labels:  entity-framework, entity-framework-core
.NET-Core-Learning-Journey
Some of the projects i made when starting to learn .NET Core
Stars: ✭ 37 (-87.67%)
Mutual labels:  entity-framework, entity-framework-core
LinqBuilder
LinqBuilder is an advanced implementation of the specification pattern specifically targeting LINQ query generation.
Stars: ✭ 34 (-88.67%)
Mutual labels:  entity-framework, entity-framework-core
MonolithicArchitecture
This repository presents an approach on how to build an application using Monolithic architecture, ASP.NET Core, EntityFrameworkCore, Identity Server, CQRS, DDD
Stars: ✭ 18 (-94%)
Mutual labels:  aspnetcore, entity-framework-core
Katmanli-Mimari-ETicaret-Core-Mvc
Baştan Sona Core Mvc ile Kendi E-Ticaret Siteni Mimari Bakış Açısıyla Hazırla.
Stars: ✭ 78 (-74%)
Mutual labels:  aspnetcore, entity-framework-core
reconciler
Update an entity graph in store to a given one by inserting, updating and removing the respective entities.
Stars: ✭ 24 (-92%)
Mutual labels:  entity-framework, entity-framework-core
OrdersManagementSystem
Project demonstrates usage of Prism composition library, Material design library, SQL Server, Entity Framework in WPF application
Stars: ✭ 29 (-90.33%)
Mutual labels:  aspnetcore, entity-framework
Authentication
Authentication examples for AspNetCore 3.1
Stars: ✭ 37 (-87.67%)
Mutual labels:  aspnetcore, entity-framework-core
Uno.SQLitePCLRaw.Wasm
An SQLiteRaw WebAssembly provider for SQLitePCLRaw.core
Stars: ✭ 25 (-91.67%)
Mutual labels:  entity-framework, entity-framework-core
NETProvider
Firebird ADO.NET Data Provider
Stars: ✭ 113 (-62.33%)
Mutual labels:  entity-framework, entity-framework-core
BlazorEFCoreMultitenant
Examples of multitenancy using EF Core and Blazor.
Stars: ✭ 67 (-77.67%)
Mutual labels:  entity-framework, entity-framework-core
run-aspnetcore-basics retired
One Solution - One Project for web application development with Asp.Net Core & EF.Core. Only one web application project which used aspnetcore components; razor pages, middlewares, dependency injection, configuration, logging. To create websites with minimum implementation of asp.net core based on HTML5, CSS, and JavaScript. You can use this boi…
Stars: ✭ 15 (-95%)
Mutual labels:  aspnetcore, entity-framework-core
CodexMicroORM
An alternative to ORM's such as Entity Framework, offers light-weight database mapping to your existing CLR objects. Visit "Design Goals" on GitHub to see more rationale and guidance.
Stars: ✭ 32 (-89.33%)
Mutual labels:  entity-framework, entity-framework-core
Efdesigner
Entity Framework visual design surface and code-first code generation for EF6, Core and beyond
Stars: ✭ 256 (-14.67%)
Mutual labels:  entity-framework, entity-framework-core
SignalR-Core-SqlTableDependency
Shows how the new SignalR Core works with hubs and sockets, also how it can integrate with SqlTableDependency API.
Stars: ✭ 36 (-88%)
Mutual labels:  aspnetcore, entity-framework
pineblog
A light-weight blogging engine written in ASP.NET Core MVC Razor Pages, using Entity Framework Core or MongoDb.
Stars: ✭ 60 (-80%)
Mutual labels:  aspnetcore, entity-framework

Announcing a better Second Level Caching Library!

EFSecondLevelCache.Core

GitHub Actions status

Entity Framework Core Second Level Caching Library.

Second level caching is a query cache. The results of EF commands will be stored in the cache, so that the same EF commands will retrieve their data from the cache rather than executing them against the database again.

Install via NuGet

To install EFSecondLevelCache.Core, run the following command in the Package Manager Console:

Nuget

PM> Install-Package EFSecondLevelCache.Core

You can also view the package page on NuGet.

This library also uses the CacheManager.Core, as a highly configurable cache manager. To use its in-memory caching mechanism, add these entries to the .csproj file:

  <ItemGroup>
    <PackageReference Include="EFSecondLevelCache.Core" Version="2.9.0" />
    <PackageReference Include="CacheManager.Core" Version="1.2.0" />
    <PackageReference Include="CacheManager.Microsoft.Extensions.Caching.Memory" Version="1.2.0" />
    <PackageReference Include="CacheManager.Serialization.Json" Version="1.2.0" />
  </ItemGroup>

And to get the latest versions of these libraries you can run the following command in the Package Manager Console:

PM> Update-Package

Usage

1- Register the required services of EFSecondLevelCache.Core and also CacheManager.Core

namespace EFSecondLevelCache.Core.AspNetCoreSample
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddEFSecondLevelCache();

            // Add an in-memory cache service provider
            services.AddSingleton(typeof(ICacheManager<>), typeof(BaseCacheManager<>));
            services.AddSingleton(typeof(ICacheManagerConfiguration),
                new CacheManager.Core.ConfigurationBuilder()
                        .WithJsonSerializer()
                        .WithMicrosoftMemoryCacheHandle(instanceName: "MemoryCache1")
                        .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(10))
                        .Build());
        }
    }
}

If you want to use the Redis as the preferred cache provider, first install the CacheManager.StackExchange.Redis package and then register its required services:

// Add Redis cache service provider
var jss = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore,
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};

const string redisConfigurationKey = "redis";
services.AddSingleton(typeof(ICacheManagerConfiguration),
    new CacheManager.Core.ConfigurationBuilder()
        .WithJsonSerializer(serializationSettings: jss, deserializationSettings: jss)
        .WithUpdateMode(CacheUpdateMode.Up)
        .WithRedisConfiguration(redisConfigurationKey, config =>
        {
            config.WithAllowAdmin()
                .WithDatabase(0)
                .WithEndpoint("localhost", 6379)
                // Enables keyspace notifications to react on eviction/expiration of items.
                // Make sure that all servers are configured correctly and 'notify-keyspace-events' is at least set to 'Exe', otherwise CacheManager will not retrieve any events.
                // See https://redis.io/topics/notifications#configuration for configuration details.
                .EnableKeyspaceEvents();
        })
        .WithMaxRetries(100)
        .WithRetryTimeout(50)
        .WithRedisCacheHandle(redisConfigurationKey)
        .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(10))
        .Build());
services.AddSingleton(typeof(ICacheManager<>), typeof(BaseCacheManager<>));

2- Setting up the cache invalidation by overriding the SaveChanges method to prevent stale reads:

namespace EFSecondLevelCache.Core.AspNetCoreSample.DataLayer
{
    public class SampleContext : DbContext
    {
        public SampleContext(DbContextOptions<SampleContext> options) : base(options)
        { }

        public virtual DbSet<Post> Posts { get; set; }

        public override int SaveChanges()
        {
            var changedEntityNames = this.GetChangedEntityNames();

            this.ChangeTracker.AutoDetectChangesEnabled = false; // for performance reasons, to avoid calling DetectChanges() again.
            var result = base.SaveChanges();
            this.ChangeTracker.AutoDetectChangesEnabled = true;

            this.GetService<IEFCacheServiceProvider>().InvalidateCacheDependencies(changedEntityNames);

            return result;
        }
    }
}

3- Then to cache the results of the normal queries like:

var products = context.Products.Include(x => x.Tags).FirstOrDefault();

We can use the new Cacheable() extension method:

// If you don't specify the `EFCachePolicy`, the global `new CacheManager.Core.ConfigurationBuilder().WithExpiration()` setting will be used automatically.
var products = context.Products.Include(x => x.Tags).Cacheable().FirstOrDefault(); // Async methods are supported too.

// Or you can specify the `EFCachePolicy` explicitly to override the global settings.
var post1 = context.Posts
                   .Where(x => x.Id > 0)
                   .OrderBy(x => x.Id)
                   .Cacheable(CacheExpirationMode.Sliding, TimeSpan.FromMinutes(5))
                   .FirstOrDefault();

// NOTE: It's better to add the `Cacheable()` method before the materialization methods such as `ToList()` or `FirstOrDefault()` to cover the whole expression tree.

Also AutoMapper's ProjectTo() method is supported:

var posts = context.Posts
                   .Where(x => x.Id > 0)
                   .OrderBy(x => x.Id)
                   .Cacheable()
                   .ProjectTo<PostDto>(configuration: _mapper.ConfigurationProvider)
                   .ToList();

Guidance

When to use

Good candidates for query caching are global site settings and public data, such as infrequently changing articles or comments. It can also be beneficial to cache data specific to a user so long as the cache expires frequently enough relative to the size of the user base that memory consumption remains acceptable. Small, per-user data that frequently exceeds the cache's lifetime, such as a user's photo path, is better held in user claims, which are stored in cookies, than in this cache.

Scope

This cache is scoped to the application, not the current user. It does not use session variables. Accordingly, when retriveing cached per-user data, be sure queries in include code such as .Where(x => .... && x.UserId == id).

Invalidation

This cache is updated when an entity is changed (insert, update, or delete) via a DbContext that uses this library. If the database is updated through some other means, such as a stored procedure or trigger, the cache becomes stale.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].