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


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

    学无止境,精益求精

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

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

        public class PaginationListModel<T>
        {
            public PaginationListModel()
            {
                Data = new List<T>();
            }
            public List<T> Data { get; set; }
            public BasePaginationModel Pagination { get; set; }
        }
    
        public class PaginationModel
        {
            #region 构造函数
    
            public PaginationModel()
            {
                PageNumber = 1;
                PageSize = 10;
            }
    
            #endregion
            /// <summary>
            /// 当前页码
            /// </summary>
            public int PageNumber { get; set; }
    
            /// <summary>
            /// 每页行数
            /// </summary>
            public int PageSize { get; set; }
    
        }
    
        /// <summary>
        /// 基本分页实体类
        /// </summary>
        public class BasePaginationModel
        {
            #region 构造函数
    
            public BasePaginationModel()
            {
                PageNumber = 1;
                PageSize = 10;
            }
    
            #endregion
    
            #region 成员
    
            /// <summary>
            /// 总页数
            /// </summary>
            public int PageCount
            {
                get
                {
                    int pages = Total / PageSize;
                    int pageCount = Total % PageSize == 0 ? pages : pages + 1;
                    return pageCount;
                }
            }
    
            /// <summary>
            /// 当前页码
            /// </summary>
            public int PageNumber { get; set; }
    
            /// <summary>
            /// 每页行数
            /// </summary>
            public int PageSize { get; set; }
    
    
            /// <summary>
            /// 总记录数
            /// </summary>
            public int Total { get; set; }
    
            /// <summary>
            /// 总页数
            /// </summary>
            public int Pages { get => PageCount; }
    
            /// <summary>
            /// 是否首页
            /// </summary>
            public bool IsFirstPage { get => PageNumber == 1; }
    
            /// <summary>
            /// 是否尾页
            /// </summary>
            public bool IsLastPage { get => PageNumber == Pages; }
    
            #endregion
        }
    View Code

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

        public static class MongoPaginationService
        {
            /// <summary>
            /// 支持排序
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="entitys"></param>
            /// <param name="pagination"></param>
            /// <returns></returns>
            public static IQueryable<T> BaseOrderPager<T>(this IOrderedQueryable<T> entitys, ref BasePaginationOrderModel pagination)
            {
                if (pagination != null)
                {
                    var result = entitys.GetBasePagination(pagination);
                    return result;
                }
                return null;
            }
    
            /// <summary>
            /// 
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="source"></param>
            /// <param name="pagination"></param>
            /// <returns></returns>
            private static IQueryable<T> GetBasePagination<T>(this IOrderedQueryable<T> source, BasePaginationOrderModel pagination)
            {
                pagination.Total = source.Count();
                return source.Skip((pagination.PageNumber - 1) * pagination.PageSize).Take(pagination.PageSize);
            }
    
            /// <summary>
            /// 分页
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="entitys"></param>
            /// <param name="json"></param>
            /// <param name="pagination"></param>
            /// <returns></returns>
            public static IQueryable<T> BasePager<T>(this IOrderedQueryable<T> entitys, ref BasePaginationModel pagination)
            {
                if (pagination != null)
                {
                    var result = entitys.GetBasePagination(pagination);
                    return result;
                }
                return null;
            }
    
            /// <summary>
            /// 获取分页后的数据
            /// </summary>
            /// <typeparam name="T">实体类型</typeparam>
            /// <param name="source">数据源IQueryable</param>
            /// <param name="pagination">分页参数</param>
            /// <returns></returns>
            private static IQueryable<T> GetBasePagination<T>(this IOrderedQueryable<T> source, BasePaginationModel pagination)
            {
                pagination.Total = source.Count();
                return source.Skip((pagination.PageNumber - 1) * pagination.PageSize).Take(pagination.PageSize);
            }
        }
    
        public static class PaginationService
        {
            /// <summary>
            /// 分页
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="entitys"></param>
            /// <param name="json"></param>
            /// <param name="pagination"></param>
            /// <returns></returns>
            public static IQueryable<T> BasePager<T>(this IQueryable<T> entitys, ref BasePaginationModel pagination)
            {
                if (pagination != null)
                    entitys = entitys.GetBasePagination(pagination);
                return entitys;
            }
    
            /// <summary>
            /// 获取分页后的数据
            /// </summary>
            /// <typeparam name="T">实体类型</typeparam>
            /// <param name="source">数据源IQueryable</param>
            /// <param name="pagination">分页参数</param>
            /// <returns></returns>
            private static IQueryable<T> GetBasePagination<T>(this IQueryable<T> source, BasePaginationModel pagination)
            {
                pagination.Total = source.Count();
                return source.Skip((pagination.PageNumber - 1) * pagination.PageSize).Take(pagination.PageSize);
            }
        }
    View Code

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

            /// <summary>
            /// 查询设备列表
            /// </summary>
            /// <param name="Data"></param>
            /// <returns></returns>
            [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<PaginationListModel<BatteryHeart2gToTb>> 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<BatteryHeart2gToTb>(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<BatteryHeart2gToTb>(q, ref Pagination);
                PaginationListModel<BatteryHeart2gToTb> M = new PaginationListModel<BatteryHeart2gToTb>()
                {
                    Data = result.ToList(),
                    Pagination = Pagination
                };
                foreach (var item in M.Data)
                {
                    item.CreateTime = item.CreateTime.AddHours(8);
                }
                return CommonBaseResponse.SetResponse<PaginationListModel<BatteryHeart2gToTb>>(M, true);
            }
    View Code

    最最后:

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

    就没有了,简单吧。

    @天才卧龙的博客

  • 相关阅读:
    Java的值传递和引用传递的说法
    将对象写道硬盘上and从硬盘上读入对象
    分割一个文件and合并一个文件(并且带有配置信息记录)
    文件的切割和合并
    SequenceInputStream的用法(用来合并流然后一起操作)
    PrintStream和PrintWrite用法
    将一个文件夹中的所有含有某个后缀的文件写进一个文件里面
    关于Properties的制作配置文件(当一个app已经5次被打开我们就收费)
    Properties的用法
    深层删除一个目录(java)
  • 原文地址:https://www.cnblogs.com/chenwolong/p/mongolinq.html
Copyright © 2020-2023  润新知