Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

451 righe
15 KiB

  1. using MongoDB.Bson;
  2. using MongoDB.Bson.Serialization.Attributes;
  3. using MongoDB.Driver;
  4. using MongoDB.Driver.Linq;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Linq.Expressions;
  9. using System.Reflection;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace DataVAPI.ServerDB.MongoDB
  13. {
  14. public class Db
  15. {
  16. private static readonly string connStr = "mongodb://localhost:27017";//"mongodb://root:cygadmin@192.168.1.224:27017";// ConfigurationManager.ConnectionStrings["connStr"].ToString();
  17. private static readonly string dbName = "iotdb";//ConfigurationManager.AppSettings["dbName"].ToString();
  18. private static IMongoDatabase db = null;
  19. private static readonly object lockHelper = new object();
  20. private Db() { }
  21. public static IMongoDatabase GetDb(string conn, string dbna)
  22. {
  23. if (db == null)
  24. {
  25. lock (lockHelper)
  26. {
  27. if (db == null)
  28. {
  29. var client = new MongoClient(conn);
  30. db = client.GetDatabase(dbna);
  31. }
  32. }
  33. }
  34. return db;
  35. }
  36. }
  37. public class MongoDbHelper<T> where T : BaseEntity
  38. {
  39. private IMongoDatabase db = null;
  40. private IMongoCollection<T> collection = null;
  41. public MongoDbHelper(string conn, string dbna)
  42. {
  43. db = Db.GetDb(conn, dbna);
  44. collection = db.GetCollection<T>(typeof(T).Name);
  45. }
  46. public T Insert(T entity)
  47. {
  48. entity.Id = ObjectId.GenerateNewId().ToString();
  49. entity.State = "y";
  50. entity.CreateTime = DateTime.Now;//.ToString("yyyy-MM-dd HH:mm:ss");
  51. entity.UpdateTime = DateTime.Now;//.ToString("yyyy-MM-dd HH:mm:ss");
  52. collection.InsertOneAsync(entity);
  53. return entity;
  54. }
  55. public List<T> Inserts(List<T> entity)
  56. {
  57. entity?.ForEach(par =>
  58. {
  59. var flag = ObjectId.GenerateNewId();
  60. par.GetType().GetProperty("Id").SetValue(par, flag);
  61. par.State = "y";
  62. par.CreateTime = DateTime.Now;
  63. par.UpdateTime = DateTime.Now;
  64. });
  65. collection.InsertManyAsync(entity);
  66. return entity;
  67. }
  68. public void Modify(string id, string field, string value)
  69. {
  70. var filter = Builders<T>.Filter.Eq("Id", id);
  71. var updated = Builders<T>.Update.Set(field, value);
  72. UpdateResult result = collection.UpdateOneAsync(filter, updated).Result;
  73. }
  74. public void UpdateID(T entity)
  75. {
  76. var old = collection.Find(e => e.Id.Equals(entity.Id))?.ToList().FirstOrDefault();
  77. foreach (var prop in entity.GetType().GetProperties())
  78. {
  79. if (prop.Name != "Id")
  80. {
  81. try
  82. {
  83. var Type = prop.PropertyType.Name;
  84. var newValue = prop.GetValue(entity);
  85. var oldValue = old.GetType().GetProperty(prop.Name).GetValue(old);
  86. if (newValue != null)
  87. {
  88. if (oldValue==null || !newValue.ToString().Equals(oldValue.ToString()))
  89. {
  90. old.GetType().GetProperty(prop.Name).SetValue(old, newValue);
  91. //if (Type == typeof(DateTime).Name)
  92. }
  93. }
  94. }
  95. catch (Exception ex)
  96. {
  97. }
  98. }
  99. }
  100. old.State = "y";
  101. old.UpdateTime = DateTime.Now;//.ToString("yyyy-MM-dd HH:mm:ss");
  102. var filter = Builders<T>.Filter.Eq("Id", entity.Id);
  103. ReplaceOneResult result = collection.ReplaceOneAsync(filter, old).Result;
  104. }
  105. public void Delete(string id)
  106. {
  107. var filter = Builders<T>.Filter.Eq("Id", id);
  108. collection.DeleteOneAsync(filter);
  109. }
  110. public T QueryOne(string id)
  111. {
  112. return collection.Find(a => a.Id == id)?.ToList().FirstOrDefault();
  113. }
  114. public List<T> QueryAllNew(string clientId, string deviceId)
  115. {
  116. if (string.IsNullOrEmpty(clientId))
  117. {
  118. return collection.Find(par=>par.Id!=null)?.ToList().OrderByDescending(a => a.CreateTime).ToList();
  119. }
  120. else
  121. {
  122. if (string.IsNullOrEmpty(deviceId))
  123. {
  124. return collection.Find(a => a.ClientId == clientId)?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
  125. }
  126. else
  127. {
  128. return collection.Find(a => a.ClientId == clientId && a.DeviceId.Contains(deviceId))?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
  129. }
  130. }
  131. }
  132. public List<T> QueryAllTime(string clientId, string deviceId, DateTime datesta, DateTime datastop)
  133. {
  134. if (string.IsNullOrEmpty(clientId))
  135. {
  136. if (datastop >= datesta && datastop > DateTime.Parse("2011-10-11 00:00:00"))
  137. {
  138. return collection.Find(a => a.CreateTime >= datesta && a.CreateTime <= datastop)?.ToList().OrderByDescending(a => a.CreateTime).ToList();
  139. }
  140. else
  141. {
  142. return collection.Find(a => a.CreateTime >= datesta)?.ToList().OrderByDescending(a => a.CreateTime).ToList();
  143. }
  144. }
  145. else
  146. {
  147. if (datastop >= datesta && datastop > DateTime.Parse("2011-10-11 00:00:00"))
  148. {
  149. //if (string.IsNullOrEmpty(deviceId))
  150. //{
  151. return collection.Find(a => a.ClientId == clientId && a.CreateTime >= datesta && a.CreateTime <= datastop)?.ToList().OrderByDescending(a => a.CreateTime).ToList();
  152. //}
  153. //else
  154. //{
  155. // return collection.Find(a => a.ClientId == clientId && a.DeviceId == deviceId && a.CreateTime >= datesta && a.CreateTime <= datastop)?.ToList().OrderByDescending(a => a.CreateTime).ToList();
  156. //}
  157. }
  158. else
  159. {
  160. if (string.IsNullOrEmpty(deviceId))
  161. {
  162. return collection.Find(a => a.ClientId == clientId)?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
  163. }
  164. else
  165. {
  166. return collection.Find(a => a.ClientId == clientId && a.DeviceId.Contains(deviceId))?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
  167. }
  168. }
  169. }
  170. }
  171. public T QueryDeviceName(string DeviceName)
  172. {
  173. return collection.Find(a => a.devicename == DeviceName && a.State == "y")?.ToList().FirstOrDefault();
  174. }
  175. public List<T> QueryClientIdNew(string clientId)
  176. {
  177. return collection.Find(a => a.ClientId == clientId && a.State == "y")?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
  178. }
  179. public List<T> QueryClientId(string clientId)
  180. {
  181. return collection.Find(a => a.ClientId == clientId && a.CreateTime >= DateTime.Now.Date)?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
  182. }
  183. public List<T> QueryClientIdNameO(string clientId, string name)
  184. {
  185. return collection.Find(a => a.ClientId == clientId && a.devicename==name && a.CreateTime >= DateTime.Now.Date)?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
  186. }
  187. public List<T> QueryClientIdName(string clientId,string name)
  188. {
  189. return collection.Find(a => a.ClientId == clientId && a.CreateTime >= DateTime.Now.AddDays(-3).Date && a.devicename==name)?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
  190. }
  191. public T QueryClientIdMax(string clientId)
  192. {
  193. List<T> clo = collection.Find(a => a.ClientId == clientId && a.CreateTime >= DateTime.Now.Date && a.State == "y")?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
  194. return clo.Count>0?clo[0]:null;
  195. }
  196. public T QueryClientIdMaxName(string clientId,string name)
  197. {
  198. 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();
  199. return clo.Count > 0 ? clo[0] : null;
  200. }
  201. public List<T> QueryDeviceId(string clientId, string deviceId)
  202. {
  203. return collection.Find(a => a.DeviceId == deviceId && a.ClientId == clientId && a.CreateTime >= DateTime.Now.Date && a.State == "y")?.ToList().OrderByDescending(a => a.CreateTime)?.ToList();
  204. }
  205. public List<T> QueryAll()
  206. {
  207. return collection.Find(a => a.State.Equals("y"))?.ToList();
  208. }
  209. public T QueryKeyID(string key)
  210. {
  211. return collection.Find(a => a.KeyID== key)?.ToList().FirstOrDefault();
  212. }
  213. public List<T> ALLData(string key)
  214. {
  215. return collection.Find(a => a.ClientId == key)?.ToList();
  216. }
  217. public List<T> ALLDataName(string key,string name)
  218. {
  219. return collection.Find(a => a.ClientId == key && a.devicename==name)?.ToList();
  220. }
  221. public PaginationListModel<T> BasePagQuery(string clientId, string deviceId, DateTime datesta, DateTime datastop, int PageNumber, int PageSize)
  222. {
  223. BasePaginationModel pagination = new BasePaginationModel()
  224. {
  225. PageNumber = PageNumber,
  226. PageSize = PageSize
  227. };
  228. var RT = GetPagination(clientId, deviceId, datesta, datastop, ref pagination);
  229. return RT;
  230. }
  231. public PaginationListModel<T> GetPagination(string clientId, string deviceId, DateTime datesta, DateTime datastop, ref BasePaginationModel Pagination)
  232. {
  233. 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);
  234. var result = mongorResult.BasePager(ref Pagination);
  235. PaginationListModel<T> M = new PaginationListModel<T>()
  236. {
  237. Data = result?.ToList(),
  238. Pagination = Pagination
  239. };
  240. return M;
  241. }
  242. }
  243. /// <summary>
  244. /// MongoDB基类
  245. /// </summary>
  246. public abstract class BaseEntity
  247. {
  248. /// <summary>
  249. /// ID
  250. /// </summary>
  251. [BsonRepresentation(BsonType.ObjectId)]
  252. public string Id { get; set; }
  253. /// <summary>
  254. /// 客户端 ID
  255. /// </summary>
  256. public string ClientId { get; set; }
  257. /// <summary>
  258. /// 设备 ID
  259. /// </summary>
  260. public string DeviceId { get; set; }
  261. /// <summary>
  262. /// 阿里云设备名称
  263. /// </summary>
  264. public string devicename { get; set; }
  265. /// <summary>
  266. /// 状态
  267. /// </summary>
  268. public string State { get; set; }
  269. /// <summary>
  270. /// 创建时间
  271. /// </summary>
  272. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  273. public DateTime CreateTime { get; set; }
  274. /// <summary>
  275. /// 修改时间
  276. /// </summary>
  277. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  278. public DateTime UpdateTime { get; set; }
  279. /// <summary>
  280. /// key
  281. /// </summary>
  282. public string KeyID { get; set; }
  283. }
  284. public static class MongoPaginationService
  285. {
  286. /// <summary>
  287. /// 分页
  288. /// </summary>
  289. /// <typeparam name="T"></typeparam>
  290. /// <param name="entitys"></param>
  291. /// <param name="json"></param>
  292. /// <param name="pagination"></param>
  293. /// <returns></returns>
  294. public static IQueryable<T> BasePager<T>(this IOrderedQueryable<T> entitys, ref BasePaginationModel pagination)
  295. {
  296. if (pagination != null)
  297. {
  298. var result = entitys.GetBasePagination(pagination);
  299. return result;
  300. }
  301. return null;
  302. }
  303. /// <summary>
  304. /// 获取分页后的数据
  305. /// </summary>
  306. /// <typeparam name="T">实体类型</typeparam>
  307. /// <param name="source">数据源IQueryable</param>
  308. /// <param name="pagination">分页参数</param>
  309. /// <returns></returns>
  310. private static IQueryable<T> GetBasePagination<T>(this IOrderedQueryable<T> source, BasePaginationModel pagination)
  311. {
  312. pagination.Total = source.Count();
  313. return source.Skip((pagination.PageNumber - 1) * pagination.PageSize).Take(pagination.PageSize);
  314. }
  315. }
  316. public class PaginationListModel<T>
  317. {
  318. public PaginationListModel()
  319. {
  320. Data = new List<T>();
  321. }
  322. public List<T> Data { get; set; }
  323. public BasePaginationModel Pagination { get; set; }
  324. }
  325. public class PaginationModel
  326. {
  327. #region 构造函数
  328. public PaginationModel()
  329. {
  330. PageNumber = 1;
  331. PageSize = 10;
  332. }
  333. #endregion
  334. /// <summary>
  335. /// 当前页码
  336. /// </summary>
  337. public int PageNumber { get; set; }
  338. /// <summary>
  339. /// 每页行数
  340. /// </summary>
  341. public int PageSize { get; set; }
  342. }
  343. /// <summary>
  344. /// 基本分页实体类
  345. /// </summary>
  346. public class BasePaginationModel
  347. {
  348. #region 构造函数
  349. public BasePaginationModel()
  350. {
  351. PageNumber = 1;
  352. PageSize = 10;
  353. }
  354. #endregion
  355. #region 成员
  356. /// <summary>
  357. /// 总页数
  358. /// </summary>
  359. public int PageCount
  360. {
  361. get
  362. {
  363. int pages = Total / PageSize;
  364. int pageCount = Total % PageSize == 0 ? pages : pages + 1;
  365. return pageCount;
  366. }
  367. }
  368. /// <summary>
  369. /// 当前页码
  370. /// </summary>
  371. public int PageNumber { get; set; }
  372. /// <summary>
  373. /// 每页行数
  374. /// </summary>
  375. public int PageSize { get; set; }
  376. /// <summary>
  377. /// 总记录数
  378. /// </summary>
  379. public int Total { get; set; }
  380. /// <summary>
  381. /// 总页数
  382. /// </summary>
  383. public int Pages { get => PageCount; }
  384. /// <summary>
  385. /// 是否首页
  386. /// </summary>
  387. public bool IsFirstPage { get => PageNumber == 1; }
  388. /// <summary>
  389. /// 是否尾页
  390. /// </summary>
  391. public bool IsLastPage { get => PageNumber == Pages; }
  392. #endregion
  393. }
  394. }