EF.Plus - Query Cache - Introduction

CSharp · Console

/Program.cs

// Entity Framework Plus
// Doc: https://entityframework-plus.net/query-cache

// @nuget: EntityFramework
// @nuget: Z.EntityFramework.Plus.EF6

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using Z.EntityFramework.Plus;

public class Program
{
	public static void Main()
	{	
		GenerateData();
		
		List<Customer> customers1 = new List<Customer>();
		List<Customer> customers2 = new List<Customer>();
		
		using (var context = new EntityContext())
		{
			// To use caching, simply append to the query "FromCache" method before using an immediate resolution method like "ToList()" or "FirstOrDefault()".
			// The first call perform a database round trip
			context.Customers.FromCache().ToList();
			
			context.Customers.OrderBy(x => x.CustomerID).Take(2).Delete();
		}
		
		using (var context = new EntityContext())
		{
			// Subsequent calls will take the value from the memory instead
			customers2 = context.Customers.FromCache().ToList();
			
			FiddleHelper.WriteTable("1 - In DataBase",context.Customers.ToList());	
			FiddleHelper.WriteTable("2 - In Cache",customers2);
		}
	}
		 
	public static void GenerateData()
	{
		
		using (var context = new EntityContext())
		{
			context.Customers.Add(new Customer() { Name ="Customer_A", IsActive = false  });
			context.Customers.Add(new Customer() { Name ="Customer_B", IsActive = true });
			context.Customers.Add(new Customer() { Name ="Customer_C", IsActive = false });

			context.SaveChanges();	
		}
	}

	public class EntityContext : DbContext
	{
		public EntityContext() : base(FiddleHelper.GetConnectionStringSqlServer())
		{

		}
		
		public DbSet<Customer> Customers { get; set; }
	}
	
	
	public class Customer
	{
		public int CustomerID { get; set; }
		public string Name { get; set; }
		public Boolean IsActive { get; set; }
	}
}
;