人性化的MongoDb Linq查询方式【带分页】,方便快捷,IQueryable<T>牛逼了、、、C#


十年河东,十年河西,莫欺少年穷

学无止境,精益求精

没什么好说了,主要是代码类的东西,分享给大家

首先,我们创建下基础的分页类库

    public class PaginationListModel
    {
        public PaginationListModel()
        {
            Data = new List();
        }
        public List Data { get; set; }
        public BasePaginationModel Pagination { get; set; }
    }

    public class PaginationModel
    {
        #region 构造函数

        public PaginationModel()
        {
            PageNumber = 1;
            PageSize = 10;
        }

        #endregion
        /// 
        /// 当前页码
        /// 
        public int PageNumber { get; set; }

        /// 
        /// 每页行数
        /// 
        public int PageSize { get; set; }

    }

    /// 
    /// 基本分页实体类
    /// 
    public class BasePaginationModel
    {
        #region 构造函数

        public BasePaginationModel()
        {
            PageNumber = 1;
            PageSize = 10;
        }

        #endregion

        #region 成员

        /// 
        /// 总页数
        /// 
        public int PageCount
        {
            get
            {
                int pages = Total / PageSize;
                int pageCount = Total % PageSize == 0 ? pages : pages + 1;
                return pageCount;
            }
        }

        /// 
        /// 当前页码
        /// 
        public int PageNumber { get; set; }

        /// 
        /// 每页行数
        /// 
        public int PageSize { get; set; }


        /// 
        /// 总记录数
        /// 
        public int Total { get; set; }

        /// 
        /// 总页数
        /// 
        public int Pages { get => PageCount; }

        /// 
        /// 是否首页
        /// 
        public bool IsFirstPage { get => PageNumber == 1; }

        /// 
        /// 是否尾页
        /// 
        public bool IsLastPage { get => PageNumber == Pages; }

        #endregion
    }

其次,我们封装下分页的方法

    public static class MongoPaginationService
    {
        /// 
        /// 支持排序
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IQueryable BaseOrderPager(this IOrderedQueryable entitys, ref BasePaginationOrderModel pagination)
        {
            if (pagination != null)
            {
                var result = entitys.GetBasePagination(pagination);
                return result;
            }
            return null;
        }

        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        private static IQueryable GetBasePagination(this IOrderedQueryable source, BasePaginationOrderModel pagination)
        {
            pagination.Total = source.Count();
            return source.Skip((pagination.PageNumber - 1) * pagination.PageSize).Take(pagination.PageSize);
        }

        /// 
        /// 分页
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IQueryable BasePager(this IOrderedQueryable entitys, ref BasePaginationModel pagination)
        {
            if (pagination != null)
            {
                var result = entitys.GetBasePagination(pagination);
                return result;
            }
            return null;
        }

        /// 
        /// 获取分页后的数据
        /// 
        /// 实体类型
        /// 数据源IQueryable
        /// 分页参数
        /// 
        private static IQueryable GetBasePagination(this IOrderedQueryable source, BasePaginationModel pagination)
        {
            pagination.Total = source.Count();
            return source.Skip((pagination.PageNumber - 1) * pagination.PageSize).Take(pagination.PageSize);
        }
    }

    public static class PaginationService
    {
        /// 
        /// 分页
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IQueryable BasePager(this IQueryable entitys, ref BasePaginationModel pagination)
        {
            if (pagination != null)
                entitys = entitys.GetBasePagination(pagination);
            return entitys;
        }

        /// 
        /// 获取分页后的数据
        /// 
        /// 实体类型
        /// 数据源IQueryable
        /// 分页参数
        /// 
        private static IQueryable GetBasePagination(this IQueryable source, BasePaginationModel pagination)
        {
            pagination.Total = source.Count();
            return source.Skip((pagination.PageNumber - 1) * pagination.PageSize).Take(pagination.PageSize);
        }
    }

最后,我们写个方法来进行查询,如下:

        /// 
        /// 查询设备列表
        /// 
        /// 
        /// 
        [HttpPost]
        public IHttpActionResult SearchBatterys([FromBody] SearchBatteryModel Data)
        {
            BasePaginationModel pagination = new BasePaginationModel()
            {
                PageNumber = Data.PageNumber,
                PageSize = Data.PageSize
            };
            var result = BatteryEchatsService.SearchBatterys(Data,ref pagination);
            return Ok(result);
        }

服务方法:

        public static BaseResponse> SearchBatterys(SearchBatteryModel data, ref BasePaginationModel Pagination)
        {
            LogstoreDatabaseSettings settings = new LogstoreDatabaseSettings() { LogsCollectionName = CommEnum.MongoDb2gBatteryEnm.Battery2gData.ToString(), DatabaseName = DatabaseName };
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(DatabaseName);
            var Mongo = database.GetCollection(settings.LogsCollectionName);
            var q = from p in Mongo.AsQueryable() 
                    select p;

            #region 查询条件
            q = q.Where(A => A.BatterySN.Length==16);
            if (!string.IsNullOrEmpty(data.BatterySN))
            {
                q = q.Where(A => A.BatterySN.Contains(data.BatterySN));
            }
            if (data.minLoopNumber.HasValue)
            {
                q = q.Where(A => A.BatteryLoopNumber>=data.minLoopNumber);
            }
            if (data.maxLoopNumber.HasValue)
            {
                q = q.Where(A => A.BatteryLoopNumber<=data.maxLoopNumber);
            }
            if (data.MinSoc.HasValue)
            {
                q = q.Where(A => A.SOC >= data.MinSoc);
            }
            if (data.MaxSoc.HasValue)
            {
                q = q.Where(A => A.SOC <= data.MaxSoc);
            }
            if (data.BmsStatus.HasValue)
            {
                q = q.Where(A => A.BmsStatus <= data.BmsStatus);
            }
            if (data.online.HasValue)
            {
                var bDate = DateTime.Now.AddHours(-8).AddMinutes(-20);
                //约束条件
                DateTime startTime = new DateTime(bDate.Year, bDate.Month, bDate.Day, bDate.Hour, bDate.Minute, bDate.Second, DateTimeKind.Utc);
              
                if (!data.online.Value)
                {
                    q = q.Where(A => A.CreateTime < startTime);
                }
                else
                {
                    q = q.Where(A => A.CreateTime >= startTime);
                }
            }
            if (data.BmsErrors.Count > 0)
            {
                foreach(var item in data.BmsErrors)
                {
                    switch (item)
                    {
                        case "0": q = q.Where(A => A.err_0== "放电过温保护");break;
                        case "1": q = q.Where(A => A.err_1 == "放电低温保护"); break;
                        case "2": q = q.Where(A => A.err_2 == "总体过压保护"); break;
                        case "3": q = q.Where(A => A.err_3 == "总体欠压保护"); break;
                        case "4": q = q.Where(A => A.err_4 == "单体过压保护"); break;
                        case "5": q = q.Where(A => A.err_5 == "单体欠压保护"); break;
                        case "6": q = q.Where(A => A.err_6 == "短路"); break;
                        case "7": q = q.Where(A => A.err_7 == "绝缘电阻过低"); break;
                        case "8": q = q.Where(A => A.err_8 == "压差过大"); break;
                        case "9": q = q.Where(A => A.err_9 == "进水故障"); break;
                        case "10": q = q.Where(A => A.err_10 == "充电过温保护"); break;
                        case "11": q = q.Where(A => A.err_11 == "充电低温保护"); break;
                        case "12": q = q.Where(A => A.err_12 == "充电过流"); break;
                        case "13": q = q.Where(A => A.err_13 == "放电过流"); break;
                    }
                }
            }
            if (data.cdCn.HasValue)
            {
                q = q.Where(A => A.cdCn == data.cdCn.Value);
            }
            if (data.fdCn.HasValue)
            {
                q = q.Where(A => A.fdCn == data.fdCn.Value);
            }
            #endregion

            var result = PaginationService.BasePager(q, ref Pagination);
            PaginationListModel M = new PaginationListModel()
            {
                Data = result.ToList(),
                Pagination = Pagination
            };
            foreach (var item in M.Data)
            {
                item.CreateTime = item.CreateTime.AddHours(8);
            }
            return CommonBaseResponse.SetResponse>(M, true);
        }

最最后:

    public class LogstoreDatabaseSettings
    {
        public string ConnectionString { get; set; } = "mongodb://127.0.0.1:27017";//连接字符串
        public string LogsCollectionName { get; set; }
        /// 
        /// 电柜的数据库名称
        /// 
        public string DatabaseName { get; set; } 
    }

就没有了,简单吧。

 优化如下:

using Iot.Common;
using Iot.Model;
using Iot.Model.BatteryTcpip;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Iot.Dal.BatteryTcpip
{
    /// 
    /// 用于存放搁置状态下的心跳数据
    /// 
    public class Battery2gHeartService
    {
        static string isDevelop = ConfigurationManager.AppSettings["isDevelop"];
         string HeartDatabaseName = string.Empty;
         string DatabaseName = string.Empty;

        
        public Battery2gHeartService()
        {
            if (isDevelop == "1")
            {
                //正式环境
                HeartDatabaseName = "BatteryHeartDB";  //正式环境
                DatabaseName = "BatteryDB";
            }
            else
            {
                //开发环境
                HeartDatabaseName = "WA_BatteryHeartDB";   //开发环境
                DatabaseName = "WA_BatteryDB";
            }
        }

        private string GetBatteryHeartDataBaseName(int month=0)
        {
            if(month==0)
                return HeartDatabaseName + "_" + DateTime.Now.Month;
            else
                return HeartDatabaseName + "_" + month;
        }

        /// 
        /// 搁置状态下 电池心跳保存到按月份的数据库
        /// 
        /// 
        public  void SaveBatteryHearts(BatteryHeart2gToTb TbModel)
        {
            LogstoreDatabaseSettings st = new LogstoreDatabaseSettings() { LogsCollectionName = CommEnum.MongoDb2gBatteryEnm.BatteryHeart2gData.ToString(), DatabaseName = GetBatteryHeartDataBaseName() };
           
            new MongoLogService(st).Create(TbModel);
        }

        /// 
        /// 获取需要访问的数据库
        /// 
        /// 充放电类型   1:搁置 2:放电 3:充电  0:读取单月库【单月库存所有数据】
        /// 表名
        /// 
        public  IMongoDatabase GetMongoDatabase(string Table,  int? cfd=null)
        {
            if (cfd.HasValue)
            {
                string dbName ;
                switch (cfd)
                {
                    case 3: dbName = DatabaseName; break;
                    case 2: dbName = DatabaseName; break;
                    case 1: dbName = GetBatteryHeartDataBaseName(); break;
                    case 0: dbName = GetBatteryHeartDataBaseName(); break;
                    default: dbName = DatabaseName; break;
                }
                LogstoreDatabaseSettings settings = new LogstoreDatabaseSettings() { LogsCollectionName = Table, DatabaseName = dbName };
                var client = new MongoClient(settings.ConnectionString);
                var database = client.GetDatabase(dbName);
                return database;
            }
            else
            {
                LogstoreDatabaseSettings settings = new LogstoreDatabaseSettings() { LogsCollectionName = Table, DatabaseName = DatabaseName };
                var client = new MongoClient(settings.ConnectionString);
                var database = client.GetDatabase(DatabaseName);
                return database;
            }
        }

    }
}

LogstoreDatabaseSettings:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;

namespace Iot.Model
{
    public class LogstoreDatabaseSettings
    {
        static string isDevelop = ConfigurationManager.AppSettings["isDevelop"];
        public LogstoreDatabaseSettings()
        {
            if (isDevelop == "1")
            {
                //正式环境
                this.ConnectionString = "mongodb://10.200.53.121:27017";//连接字符串127.0.0.1
            }
            else
            {
                this.ConnectionString = "mongodb://10.200.53.122:27017";//连接字符串127.0.0.1
            }
        }
        public string ConnectionString { get; set; }
        public string LogsCollectionName { get; set; }
        /// 
        /// 电柜的数据库名称
        /// 
        public string DatabaseName { get; set; } = "LogstoreDb" + "_" + DateTime.Now.ToString("yyyyMMdd");
    }

    public class LogstoreDatabaseSettings_mongoServer_2
    {
        public string ConnectionString { get; set; } = "mongodb://10.200.53.122:27017";//连接字符串
        public string LogsCollectionName { get; set; }
        /// 
        /// 电柜的数据库名称
        /// 
        public string DatabaseName { get; set; } = "LogstoreDb" + "_" + DateTime.Now.ToString("yyyyMMdd");
    }
}

实现方法:

 public static BaseResponse GetBatteryReport(string BatterySN)
        {
            var database = new Battery2gHeartService().GetMongoDatabase(CommEnum.MongoDb2gBatteryEnm.BatteryHeart2gData.ToString(), 3);
            var Mongo = database.GetCollection(CommEnum.MongoDb2gBatteryEnm.BatteryHeart2gData.ToString());
            var q = from p in Mongo.AsQueryable().Where(A=>A.BatterySN==BatterySN)
                    select new Battery24HourseSocModel { CreateTime = p.CreateTime, Soc = p.SOC, BatterySN = p.BatterySN };

            ///开始时间
            var bDate = Convert.ToDateTime(DateTime.Now.AddHours(-24)).AddHours(-8).AddSeconds(-1);
            //约束条件
            DateTime startTime = new DateTime(bDate.Year, bDate.Month, bDate.Day, bDate.Hour, bDate.Minute, bDate.Second, DateTimeKind.Utc);

            ///结束时间
            var eDate = Convert.ToDateTime(DateTime.Now).AddHours(-8).AddSeconds(1);
            //约束条件
            DateTime endTime = new DateTime(eDate.Year, eDate.Month, eDate.Day, eDate.Hour, eDate.Minute, eDate.Second, DateTimeKind.Utc);

            q = q.Where(A => A.CreateTime >= startTime);
            q = q.Where(A => A.CreateTime <= endTime);

            var result_soc = q.ToList();
}

@天才卧龙的博客