本節目錄 介紹 定義Filter 設置Filter 這是Abp中多租戶、軟刪除、激活\禁用等如此方便的原因 Install-Package EntityFramework.DynamicFilters 定義數據 class DemoDb : DbContext { public DemoDb() :
本節目錄
- 介紹
- 定義Filter
- 設置Filter
這是Abp中多租戶、軟刪除、激活\禁用等如此方便的原因
Install-Package EntityFramework.DynamicFilters
定義數據
class DemoDb : DbContext { public DemoDb() : base("Default") { } public IDbSet<Blog> Blogs { get; set; } } interface ISoftDelete { bool IsDeleted { get; set; } } class Blog : ISoftDelete { public int Id { get; set; } public string Name { get; set; } public bool IsDeleted { get; set; } }
初始化數據
static void Main(string[] args) { using (var db = new DemoDb()) { for (int i = 0; i < 5; i++) { db.Blogs.Add(new Blog { Name = i.ToString() }); } for (int i = 0; i < 5; i++) { db.Blogs.Add(new Blog { Name = i.ToString(), IsDeleted = true }); } db.SaveChanges(); } Console.WriteLine("Done"); Console.ReadLine(); }
查詢數據
private static void Query() { using (var db = new DemoDb()) { Console.WriteLine(db.Blogs.Count()); } }
定義Filter
protected override void OnModelCreating(DbModelBuilder modelBuilder) { //以下幾種效果均一樣 modelBuilder.Filter("IsDeleted", (ISoftDelete entity) => entity.IsDeleted, false); //modelBuilder.Filter("IsDeleted", (ISoftDelete entity) => entity.IsDeleted == false); //modelBuilder.Filter("IsDeleted", (Blog entity) => entity.IsDeleted, () => //{ // //todo other // return false; //}); //多參數情況 modelBuilder.Filter("BlogFilter", (Blog b, int id, bool isDeleted) => (b.Id == id) && (b.IsDeleted == isDeleted), () => 1, () => false); }
設置Filter
修改參數值
private static void Query() { using (var db = new DemoDb()) { db.SetFilterScopedParameterValue("IsDeleted", true); db.SetFilterScopedParameterValue("BlogFilter", "id", 2); Console.WriteLine(db.Blogs.Count()); } }
啟用/禁用過濾
禁用代碼:
context.DisableFilter("IsDeleted");
context.DisableAllFilter();
modelBuilder.DisableFilterGlobally("IsDeleted");
啟用代碼:
context.EnableFilter();
context.EnableAllFilter();
參考:
https://github.com/jcachat/EntityFramework.DynamicFilters
本文地址:http://www.cnblogs.com/neverc/p/5258184.html