过滤器

1.创建过滤器

 public static SqlSugarClient GetInstance()
   {
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() 
            { DbType = DbType.SqlServer, ConnectionString =".xxxx",IsAutoCloseConnection =true});
            //单表过滤器
            db.QueryFilter.Add(new SqlFilterItem()
            {
                FilterValue = filterDb =>
                {
                    //Writable logic
                    return new SqlFilterResult() { Sql = " isDelete=0"  };//过滤器字符串更好
                }
            });
            //多表过滤器
            db.QueryFilter.Add(new SqlFilterItem()
            {
                FilterValue = filterDb =>
                {
                    //Writable logic
                    return new SqlFilterResult() { Sql = " main.isDelete=0" };
                },
                IsJoinQuery=true
            });
            //指定过滤器
            db.QueryFilter.Add(new SqlFilterItem()
            {
                FilterName= "Myfilter",// Name
                FilterValue = filterDb =>
                {
                    //Writable logic
                    return new SqlFilterResult() { Sql = "Name='jack'" };
                }
            });
            return db;
    }


2.使用上面的过滤器

//单表全局过滤器
var sql = db.Queryable<Order>().ToSql();
//SELECT [Id],[Name],[Price],[CreateTime] FROM [Order]  WHERE  isDelete=0
//多表全局过滤器
var sql2 = db.Queryable<Order,OrderItem>((main,ot)=> main.Id==ot.OrderId).ToSql();
//SELECT [Id],[Name],[Price],[CreateTime] FROM [Order] main  ,[OrderDetail]  ot  WHERE ( [main].[Id] = [ot].[OrderId] )  AND  main.isDelete=0
//执行Myfilter过滤器 并且也会执行单表过滤器
var sql3 = db.Queryable<Order>().Filter("Myfilter").ToSql();
//SELECT [Id],[Name],[Price],[CreateTime] FROM [Order]  WHERE Name='jack'    AND  isDelete=0
//只执行Myfilter过滤器,禁用单表过滤器
var sql4 = db.Queryable<Order>().Filter("Myfilter",isDisabledGobalFilter:true).ToSql();
//SELECT [Id],[Name],[Price],[CreateTime] FROM [Order]  WHERE Name='jack'

//什么过滤器也不执行
var sql5 = db.Queryable<Order>().Filter(null,isDisabledGobalFilter:true).ToSql();
//SELECT [Id],[Name],[Price],[CreateTime] FROM [Order]