[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

posted @ 2016-03-10 15:46  Never、C  阅读(1830)  评论(2编辑  收藏  举报