EF Classic - QueryResultFilter - Documentation - QueryResultFilterManager.Filter<T>(string id, Expression<Func<T, bool>> filter) (EF Core)

CSharp · Console

/Program.cs

// Entity Framework Classic
// Doc: https://entityframework-classic.net/query-result-filter

// @nuget: Z.EntityFramework.Classic

using System;
using System.Linq;
using System.Data.Entity;

public class Program
{
	public static void Main()
	{
		GenerateData();

		using (var context = new EntityContext())
		{
			// Filter an entity type using a predicate. The `QueryFilter` will be created with the specified ID.
			context.Configuration.QueryResultFilter.Filter<ISoftDelete>("id_001", customer => !customer.IsDeleted || context.DisplaySoftDelete());
			
			// SELECT * FROM Customers WHERE IsDeleted = 0
			var list = context.Customers.ToList();
			
			FiddleHelper.WriteTable("Customers", list);			
		}
	}
		 
	public static void GenerateData()
	{
		using (var context = new EntityContext())
		{
			context.Customers.Add(new Customer() { Name = "Customer_A", Description = "Description" });
			context.Customers.Add(new Customer() { Name = "Customer_B", Description = "Description", IsDeleted = true });			
			context.Customers.Add(new Customer() { Name = "Customer_C", Description = "Description" });
			
			context.SaveChanges();	
		}
	}

	public class EntityContext : DbContext
	{
		public EntityContext() : base(FiddleHelper.GetConnectionStringSqlServer())
		{		
		}
		
		public bool DisplaySoftDelete()
		{
			// Check for example if current user has admin right
			return false;
		}
		
		public DbSet<Customer> Customers { get; set; }
	}
	
	public interface ISoftDelete
	{
		bool IsDeleted { get; set; }
	}
	
	public class Customer : ISoftDelete
	{
		public int CustomerID { get; set; }
		public string Name { get; set; }
		public string Description { get; set; }
		public bool IsDeleted { get; set; }
	}
}
;