[Architect] Abp 框架原理解析(3) DynamicFilters
本节目录
- 介绍
- 定义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
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果觉得还有帮助的话,可以点一下右下角的【推荐】,希望能够持续的为大家带来好的技术文章!想跟我一起进步么?那就【关注】我吧。