CSharp · Console
// Entity Framework Plus
// Doc: https://entityframework-plus.net/query-filter
// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Plus.EFCore
using System;
using System.Linq;
using Z.EntityFramework.Plus;
using Microsoft.EntityFrameworkCore;
using Microsoft.Data.SqlClient;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
using (var context = new EntityContext())
{
context.Database.EnsureCreated();
}
GenerateData();
using (var context = new EntityContext())
{
// CREATE filter by interface
context.Filter<IAnimal>(MyEnum.EnumValue1, q => q.Where(x => x.IsDomestic));
// DISABLE filter only for class inheriting from BaseDog
context.Filter(MyEnum.EnumValue1).Disable();
// SELECT * FROM Dog
FiddleHelper.WriteTable("DISABLE filter", context.Dogs.ToList());
// ENABLE filter
context.Filter(MyEnum.EnumValue1).Enable();
// SELECT * FROM Dog WHERE IsDomestic = true
FiddleHelper.WriteTable("ENABLE filter", context.Dogs.ToList());
}
}
public static void GenerateData()
{
using (var context = new EntityContext())
{
context.Dogs.Add(new Dog() { Name = "Dog_A", Age = 3, IsDangerous = true, IsDomestic = true });
context.Dogs.Add(new Dog() { Name = "Dog_B", Age = 7, IsDangerous = false, IsDomestic = true });
context.Dogs.Add(new Dog() { Name = "Dog_C", Age = 4, IsDangerous = true, IsDomestic = false });
context.Cats.Add(new Cat() { Name = "Cat_A", Age = 1, IsDomestic = true });
context.Cats.Add(new Cat() { Name = "Cat_B", Age = 2, IsDomestic = true });
context.Cats.Add(new Cat() { Name = "Cat_C", Age = 1, IsDomestic = false });
context.SaveChanges();
}
}
public class EntityContext : DbContext
{
public EntityContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));
base.OnConfiguring(optionsBuilder);
}
public DbSet<Dog> Dogs { get; set; }
public DbSet<Cat> Cats { get; set; }
}
interface IAnimal
{
string Name { get; set; }
int Age { get; set; }
bool IsDomestic { get; set; }
}
public class BaseDog : IAnimal
{
public int DogId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool IsDomestic { get; set; }
public bool IsDangerous { get; set; }
}
public class Dog : BaseDog
{ }
public class Cat : IAnimal
{
public int CatId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool IsDomestic { get; set; }
}
public enum MyEnum
{
EnumValue1,
EnumValue2,
EnumValue3
}
}