|
- using MongoDB.Bson;
- using MongoDB.Bson.Serialization.Attributes;
- using MongoDB.Driver;
- using MongoDB.Driver.Linq;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace DataVAPI.ServerDB.MongoDB
- {
- public class Db
- {
- private static readonly string connStr = "mongodb://localhost:27017";//"mongodb://root:cygadmin@192.168.1.224:27017";// ConfigurationManager.ConnectionStrings["connStr"].ToString();
-
- private static readonly string dbName = "iotdb";//ConfigurationManager.AppSettings["dbName"].ToString();
-
- private static IMongoDatabase db = null;
-
- private static readonly object lockHelper = new object();
-
- private Db() { }
-
- public static IMongoDatabase GetDb(string conn, string dbna)
- {
- if (db == null)
- {
- lock (lockHelper)
- {
- if (db == null)
- {
- var client = new MongoClient(conn);
- db = client.GetDatabase(dbna);
- }
- }
- }
- return db;
- }
- }
-
- public class MongoDbHelper<T> where T : BaseEntity
- {
- private IMongoDatabase db = null;
-
- private IMongoCollection<T> collection = null;
-
- public MongoDbHelper(string conn, string dbna)
- {
- db = Db.GetDb(conn, dbna);
- collection = db.GetCollection<T>(typeof(T).Name);
- }
-
- public T Insert(T entity)
- {
- entity.Id = ObjectId.GenerateNewId().ToString();
- entity.State = "y";
- entity.CreateTime = DateTime.Now;//.ToString("yyyy-MM-dd HH:mm:ss");
- entity.UpdateTime = DateTime.Now;//.ToString("yyyy-MM-dd HH:mm:ss");
- collection.InsertOneAsync(entity);
- return entity;
- }
-
- public List<T> Inserts(List<T> entity)
- {
- entity?.ForEach(par =>
- {
- var flag = ObjectId.GenerateNewId();
- par.GetType().GetProperty("Id").SetValue(par, flag);
- par.State = "y";
- par.CreateTime = DateTime.Now;
- par.UpdateTime = DateTime.Now;
- });
- collection.InsertManyAsync(entity);
- return entity;
- }
-
- public void Modify(string id, string field, string value)
- {
- var filter = Builders<T>.Filter.Eq("Id", id);
- var updated = Builders<T>.Update.Set(field, value);
- UpdateResult result = collection.UpdateOneAsync(filter, updated).Result;
- }
-
- public void UpdateID(T entity)
- {
- var old = collection.Find(e => e.Id.Equals(entity.Id))?.ToList().FirstOrDefault();
-
- foreach (var prop in entity.GetType().GetProperties())
- {
- if (prop.Name != "Id")
- {
- try
- {
- var Type = prop.PropertyType.Name;
- var newValue = prop.GetValue(entity);
- var oldValue = old.GetType().GetProperty(prop.Name).GetValue(old);
- if (newValue != null)
- {
- if (oldValue==null || !newValue.ToString().Equals(oldValue.ToString()))
- {
- old.GetType().GetProperty(prop.Name).SetValue(old, newValue);
- //if (Type == typeof(DateTime).Name)
- }
- }
- }
- catch (Exception ex)
- {
-
- }
- }
- }
- old.State = "y";
- old.UpdateTime = DateTime.Now;//.ToString("yyyy-MM-dd HH:mm:ss");
-
- var filter = Builders<T>.Filter.Eq("Id", entity.Id);
- ReplaceOneResult result = collection.ReplaceOneAsync(filter, old).Result;
- }
-
- public void Delete(string id)
- {
- var filter = Builders<T>.Filter.Eq("Id", id);
- collection.DeleteOneAsync(filter);
- }
-
- public T QueryOne(string id)
- {
- return collection.Find(a => a.Id == id)?.ToList().FirstOrDefault();
- }
-
- public List<T> QueryAllNew(string clientId, string deviceId)
- {
- if (string.IsNullOrEmpty(clientId))
- {
- return collection.Find(par=>par.Id!=null)?.ToList().OrderByDescending(a => a.CreateTime).ToList();
- }
- else
- {
- if (string.IsNullOrEmpty(deviceId))
- {
- return collection.Find(a => a.ClientId == clientId)?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
- }
- else
- {
- return collection.Find(a => a.ClientId == clientId && a.DeviceId.Contains(deviceId))?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
- }
- }
- }
-
- public List<T> QueryAllTime(string clientId, string deviceId, DateTime datesta, DateTime datastop)
- {
- if (string.IsNullOrEmpty(clientId))
- {
- if (datastop >= datesta && datastop > DateTime.Parse("2011-10-11 00:00:00"))
- {
- return collection.Find(a => a.CreateTime >= datesta && a.CreateTime <= datastop)?.ToList().OrderByDescending(a => a.CreateTime).ToList();
- }
- else
- {
- return collection.Find(a => a.CreateTime >= datesta)?.ToList().OrderByDescending(a => a.CreateTime).ToList();
- }
- }
- else
- {
- if (datastop >= datesta && datastop > DateTime.Parse("2011-10-11 00:00:00"))
- {
- //if (string.IsNullOrEmpty(deviceId))
- //{
- return collection.Find(a => a.ClientId == clientId && a.CreateTime >= datesta && a.CreateTime <= datastop)?.ToList().OrderByDescending(a => a.CreateTime).ToList();
- //}
- //else
- //{
- // return collection.Find(a => a.ClientId == clientId && a.DeviceId == deviceId && a.CreateTime >= datesta && a.CreateTime <= datastop)?.ToList().OrderByDescending(a => a.CreateTime).ToList();
- //}
- }
- else
- {
- if (string.IsNullOrEmpty(deviceId))
- {
- return collection.Find(a => a.ClientId == clientId)?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
- }
- else
- {
- return collection.Find(a => a.ClientId == clientId && a.DeviceId.Contains(deviceId))?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
- }
- }
- }
- }
-
- public T QueryDeviceName(string DeviceName)
- {
- return collection.Find(a => a.devicename == DeviceName && a.State == "y")?.ToList().FirstOrDefault();
- }
-
- public List<T> QueryClientIdNew(string clientId)
- {
- return collection.Find(a => a.ClientId == clientId && a.State == "y")?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
- }
-
- public List<T> QueryClientId(string clientId)
- {
- return collection.Find(a => a.ClientId == clientId && a.CreateTime >= DateTime.Now.Date)?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
- }
-
- public List<T> QueryClientIdNameO(string clientId, string name)
- {
- return collection.Find(a => a.ClientId == clientId && a.devicename==name && a.CreateTime >= DateTime.Now.Date)?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
- }
-
- public List<T> QueryClientIdName(string clientId,string name)
- {
- return collection.Find(a => a.ClientId == clientId && a.CreateTime >= DateTime.Now.AddDays(-3).Date && a.devicename==name)?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
- }
-
- public T QueryClientIdMax(string clientId)
- {
- List<T> clo = collection.Find(a => a.ClientId == clientId && a.CreateTime >= DateTime.Now.Date && a.State == "y")?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
- return clo.Count>0?clo[0]:null;
- }
-
- public T QueryClientIdMaxName(string clientId,string name)
- {
- List<T> clo = collection.Find(a => a.ClientId == clientId && a.devicename==name && a.CreateTime >= DateTime.Now.AddDays(-3).Date && a.State == "y")?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
- return clo.Count > 0 ? clo[0] : null;
- }
-
- public List<T> QueryDeviceId(string clientId, string deviceId)
- {
- return collection.Find(a => a.DeviceId == deviceId && a.ClientId == clientId && a.CreateTime >= DateTime.Now.Date && a.State == "y")?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
- }
-
- public List<T> QueryAll()
- {
- return collection.Find(a => a.State.Equals("y"))?.ToList();
- }
-
- public T QueryKeyID(string key)
- {
- return collection.Find(a => a.KeyID== key)?.ToList().FirstOrDefault();
- }
-
- public List<T> ALLData(string key)
- {
- return collection.Find(a => a.ClientId == key)?.ToList();
- }
-
- public List<T> ALLDataName(string key,string name)
- {
- return collection.Find(a => a.ClientId == key && a.devicename==name)?.ToList();
- }
-
- public PaginationListModel<T> BasePagQuery(string clientId, string deviceId, DateTime datesta, DateTime datastop, int PageNumber, int PageSize)
- {
- BasePaginationModel pagination = new BasePaginationModel()
- {
- PageNumber = PageNumber,
- PageSize = PageSize
- };
-
- var RT = GetPagination(clientId, deviceId, datesta, datastop, ref pagination);
- return RT;
- }
-
- public PaginationListModel<T> GetPagination(string clientId, string deviceId, DateTime datesta, DateTime datastop, ref BasePaginationModel Pagination)
- {
- var mongorResult = collection.AsQueryable().Where(A => !string.IsNullOrEmpty(A.ClientId) && A.ClientId == clientId && A.DeviceId == deviceId && A.CreateTime >= datesta && A.CreateTime <= datastop).OrderByDescending(item => item.CreateTime);
- var result = mongorResult.BasePager(ref Pagination);
- PaginationListModel<T> M = new PaginationListModel<T>()
- {
- Data = result?.ToList(),
- Pagination = Pagination
- };
- return M;
- }
- }
- /// <summary>
- /// MongoDB基类
- /// </summary>
- public abstract class BaseEntity
- {
- /// <summary>
- /// ID
- /// </summary>
- [BsonRepresentation(BsonType.ObjectId)]
- public string Id { get; set; }
- /// <summary>
- /// 客户端 ID
- /// </summary>
- public string ClientId { get; set; }
- /// <summary>
- /// 设备 ID
- /// </summary>
- public string DeviceId { get; set; }
- /// <summary>
- /// 阿里云设备名称
- /// </summary>
- public string devicename { get; set; }
- /// <summary>
- /// 状态
- /// </summary>
- public string State { get; set; }
- /// <summary>
- /// 创建时间
- /// </summary>
- [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
- public DateTime CreateTime { get; set; }
- /// <summary>
- /// 修改时间
- /// </summary>
- [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
- public DateTime UpdateTime { get; set; }
- /// <summary>
- /// key
- /// </summary>
- public string KeyID { get; set; }
- }
-
-
- public static class MongoPaginationService
- {
- /// <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 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
- }
- }
|