YFMongoDBModelBase类是个模板类,对模板参数进行了约束YFMongoEntityBase,必须要继承YFMongoEntityBase
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using MongoDB.Driver; namespace Servers.Core { // MongoDBModel 基类 //要继承YFMongoEntityBase public abstract class YFMongoDBModelBase<T> where T : YFMongoEntityBase, new() { #region 子类需要实现的属性 //MongoDB的客户端类(MongoDB是服务器,链接MongoDb的服务器就变成了客户端了) protected abstract MongoClient Client { get; } //数据库名称 protected abstract string DatabaseName { get; } //集合名称(对应的是Mysql或者是SqlServer中的Table) protected abstract string CollectionName { get; } //是否记录错误日志(这个一般都要开启的吧?) protected virtual bool CanLogError { get { return false; } } #endregion #region 获取文档集合 GetCollection //写了类型之后是会把Mongo中的二进制数据实例化成这个entity类?? private IMongoCollection<T> m_Collection = null; //获取文档集合(get某个类型的Collection,相当于获取某个类型的Table,不过怎么感觉那么奇怪) public IMongoCollection<T> GetCollection() { try { if (null == m_Collection) { IMongoDatabase database = Client.GetDatabase(DatabaseName); m_Collection = database.GetCollection<T>(CollectionName); } return m_Collection; } catch (Exception e) { if (CanLogError) { //TODO:log类还没写,后面有了log类之后这里的log打印要补上 } else { throw e; } return null; } } #endregion #region GetEntity 根据编号查询实体 //根据编号查询实体 public T GetEntity(long YFId) { try { IMongoCollection<T> collection = GetCollection(); FilterDefinition<T> filter = Builders<T>.Filter.Eq("YFId", YFId); return collection.Find(filter).FirstOrDefault(); } catch (Exception e) { if (CanLogError) { //TODO:记录错误日志 } else { throw e; } return null; } } //异步根据编号查询实体 public async Task<T> GetEntityAsync(long YFId) { try { IMongoCollection<T> collection = GetCollection(); FilterDefinition<T> filter = Builders<T>.Filter.Eq("YFId", YFId); return await collection.Find(filter).FirstOrDefaultAsync(); } catch (Exception e) { if (CanLogError) { //TODO:记录错误日志 } else { throw e; } return null; } } //根据条件查询实体 public T GetEntity(FilterDefinition<T> filter) { try { IMongoCollection<T> collection = GetCollection(); return collection.Find(filter).FirstOrDefault(); } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } return null; } } //异步根据条件查询实体 public async Task<T> GetEntityAsync(FilterDefinition<T> filter) { try { IMongoCollection<T> collection = GetCollection(); return await collection.Find(filter).FirstOrDefaultAsync(); } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } return null; } } #endregion #region 查询数量 //查询数量(传进去一个规则策略,寻找符合规则的集合数量) public long GetCount(FilterDefinition<T> filter) { try { IMongoCollection<T> collection = GetCollection(); return collection.CountDocuments(filter); } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } return 0; } } //异步查询数量 public async Task<long> GetCountAsync(FilterDefinition<T> filter) { try { IMongoCollection<T> collection = GetCollection(); return await collection.CountDocumentsAsync(filter); } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } return 0; } } #endregion #region 根据条件查询数据集合 /// <summary> /// 异步根据条件查询数据集合 /// </summary> /// <param name="filter">过滤条件</param> /// <param name="sort">排序</param> /// <param name="skip">跳过</param> /// <param name="limit">限制数量</param> public List<T> GetList(FilterDefinition<T> filter, out long count, string[] field = null, SortDefinition<T> sort = null) { try { IMongoCollection<T> collection = GetCollection(); count = collection.CountDocuments(filter); //不指定查询字段??? if (field == null || field.Length == 0) { if (sort == null) return collection.Find(filter).ToList(); //如果有排序规则,进行排序 return collection.Find(filter).Sort(sort).ToList(); } //这个的直接翻译叫投影,可以理解成一种投影关系,包含这个名字的(但是不知道include是查找所有的json字符串吗?) List<ProjectionDefinition<T>> fieldList = new List<ProjectionDefinition<T>>(); for (int i=0;i< fieldList.Count;++i) { fieldList.Add(Builders<T>.Projection.Include(fieldList[i].ToString())); } ProjectionDefinition<T> projection = Builders<T>.Projection.Combine(fieldList); //可空类型,不为空就调用Clear fieldList?.Clear(); //没排序规则,就不排序 if (sort == null) return collection.Find(filter).Project<T>(projection).ToList(); //三重规则??mmp return collection.Find(filter).Sort(sort).Project<T>(projection).ToList(); } catch(Exception e) { if (CanLogError) { } else { throw e; } count = 0; return null; } } /// <summary> /// 异步根据条件查询数据集合 /// </summary> /// <param name="filter">过滤条件</param> /// <param name="sort">排序</param> /// <param name="skip">跳过</param> /// <param name="limit">限制数量</param> public async Task<List<T>> GetListAsync(FilterDefinition<T> filter,string[] field = null, SortDefinition<T> sort = null) { try { IMongoCollection<T> collection = GetCollection(); //count = collection.CountDocuments(filter); if (field == null || field.Length == 0) { if (sort == null) return await collection.Find(filter).ToListAsync(); //如果有排序规则,进行排序 return await collection.Find(filter).Sort(sort).ToListAsync(); } //这个的直接翻译叫投影,可以理解成一种投影关系,包含这个名字的(但是不知道include是查找所有的json字符串吗?) List<ProjectionDefinition<T>> fieldList = new List<ProjectionDefinition<T>>(); for (int i = 0; i < fieldList.Count; ++i) { fieldList.Add(Builders<T>.Projection.Include(fieldList[i].ToString())); } ProjectionDefinition<T> projection = Builders<T>.Projection.Combine(fieldList); //可空类型,不为空就调用Clear fieldList?.Clear(); //没排序规则,就不排序 if (sort == null) return await collection.Find(filter).Project<T>(projection).ToListAsync(); return await collection.Find(filter).Sort(sort).Project<T>(projection).ToListAsync(); } catch (Exception e) { if (CanLogError) { } else { throw e; } //count = 0; return null; } } /// <summary> /// 查询分页集合 /// </summary> /// <param name="filter">过滤器</param> /// <param name="pageSize">每页数量</param> /// <param name="pageIndex">当前页</param> /// <param name="count">总数量</param> /// <param name="field">字段</param> /// <param name="sort">排序</param> public List<T> GetListByPage(FilterDefinition<T>filter,int pageSize,int pageIndex,out long count,string[] field=null,SortDefinition<T>sort=null) { try { IMongoCollection<T> collection = GetCollection(); count = collection.CountDocuments(filter); //不查询指定字段 if (field == null || field.Length == 0) { if (sort == null) return collection.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList(); //如果有排序规则进行排序 collection.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList(); } //制定查询字段 List<ProjectionDefinition<T>> fieldList = new List<ProjectionDefinition<T>>(); for (int i = 0; i < field.Length; ++i) { fieldList.Add(Builders<T>.Projection.Include(field[i].ToString())); } ProjectionDefinition<T> projection =Builders<T>.Projection.Combine(fieldList); fieldList?.Clear(); //不排序 if(sort==null) return collection.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList(); //先投影再排序?这样投影出来的不久不会参与排序了嘛? return collection.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList(); } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } count = 0; return null; } } /// <summary> /// 异步查询分页集合 /// </summary> /// <param name="filter">过滤器</param> /// <param name="pageSize">每页数量</param> /// <param name="pageIndex">当前页</param> /// <param name="field">字段</param> /// <param name="sort">排序</param> public async Task<List<T>> GetListByPageAsync(FilterDefinition<T> filter, int pageSize, int pageIndex, string[] field = null, SortDefinition<T> sort = null) { try { IMongoCollection<T> collection = GetCollection(); //count = collection.CountDocuments(filter); //不查询指定字段 if (field == null || field.Length == 0) { if (sort == null) return await collection.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); //如果有排序规则进行排序 collection.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList(); } //制定查询字段 List<ProjectionDefinition<T>> fieldList = new List<ProjectionDefinition<T>>(); for (int i = 0; i < field.Length; ++i) { fieldList.Add(Builders<T>.Projection.Include(field[i].ToString())); } ProjectionDefinition<T> projection = Builders<T>.Projection.Combine(fieldList); fieldList?.Clear(); //不排序 if (sort == null) return await collection.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); return await collection.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } //count = 0; return null; } } #endregion #region Add添加实体 //添加实体 public void Add(T entity) { try { IMongoCollection<T> collection = GetCollection(); collection.InsertOne(entity); } catch (Exception e) { if (CanLogError) { } else { throw e; } } } //异步添加实体 public async Task AddAsync(T entity) { try { IMongoCollection<T> collection = GetCollection(); await collection.InsertOneAsync(entity); } catch (Exception e) { if (CanLogError) { } else { throw e; } } } #endregion #region AddMany 添加多个实体 //添加多个实体 public void AddMany(List<T> lst) { try { IMongoCollection<T> collection = GetCollection(); collection.InsertMany(lst); } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } } } //异步添加多个实体 public async Task AddManyAsync(List<T> lst) { try { IMongoCollection<T> collection = GetCollection(); await collection.InsertManyAsync(lst); } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } } } #endregion #region Update 修改实体 //修改实体 public void Update(T entity) { try { IMongoCollection<T> collection = GetCollection(); FilterDefinition<T> filter = Builders<T>.Filter.Eq("YFId", entity.YFId); collection.FindOneAndReplace(filter,entity); } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } } } //异步修改实体 public async Task UpdateAsync(T entity) { try { IMongoCollection<T> collection = GetCollection(); FilterDefinition<T> filter = Builders<T>.Filter.Eq("YFId", entity.YFId); await collection.FindOneAndReplaceAsync(filter, entity); } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } } } #endregion #region 删除实体 //删除实体 public void Delete(long YFId) { try { T entity = GetEntity(YFId); if (null != entity) { entity.Status = DataStatus.Delete; Update(entity); } } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } } } //异步删除实体 public async Task DeleteAsync(long YFId) { try { T entity = await GetEntityAsync(YFId); if (null != entity) { entity.Status = DataStatus.Delete; await UpdateAsync(entity); } } catch (Exception e) { if (CanLogError) { //TODO: } else { throw e; } } } #endregion #region 删除所有文档 public void DeletaAll() { try { //删库跑路了??drop这个table IMongoDatabase database = Client.GetDatabase(DatabaseName); database.DropCollection(CollectionName); //drop了为啥还要再create一下?为了完全覆盖内存吗??? database.CreateCollection(CollectionName); } catch (Exception e) { if (CanLogError) { //TODO } else { throw e; } } } public async Task DeletaAllAsync() { try { IMongoDatabase database = Client.GetDatabase(DatabaseName); await database.DropCollectionAsync(CollectionName); await database.CreateCollectionAsync(CollectionName); } catch (Exception e) { if (CanLogError) { //TODO } else { throw e; } } } #endregion } }