using MadRunFabric.Common.DbContext; using MadRunFabric.Common.Options; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MongoDB.Bson; using MongoDB.Driver; using System; using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace MadRunFabric.Common { public abstract class BaseRepository : IRepository where T : class, IBaseModel { private readonly ILogger> _logger; protected BaseContext _context; protected readonly IMongoCollection _collection; public BaseRepository(IOptions settings, ILogger> logger) { _logger = logger; _context = new BaseContext(settings); _collection = _context.GetCollection();//获取集合 } /// /// 异步添加一条数据 /// /// /// public async Task Add(T entity) { try { await _collection.InsertOneAsync(entity); return true; } catch (Exception ex) { _logger.LogError(ex.ToString()); return false; } } /// /// 异步添加多条数据 /// /// /// public async Task AddRange(List entitys) { try { await _collection.InsertManyAsync(entitys); return true; } catch (Exception ex) { _logger.LogError(ex.ToString()); return false; } } /// /// 获取数量 /// /// /// public async Task Count(Expression> @where = null) { try { return await _collection.CountAsync(@where); } catch (Exception ex) { _logger.LogError(ex.ToString()); throw ex; } } public void Dispose() { throw new NotImplementedException(); } /// /// 依据条件查询数据 /// /// /// public async Task> Get(Expression> @where = null) { try { var task = await _collection.FindAsync(@where); return task.ToList(); } catch (Exception ex) { _logger.LogError(ex.ToString()); throw ex; } } /// /// 依据查询条件查询所有数据 包含显示字段 排序 /// /// /// /// /// public async Task> Get(FilterDefinition filter, string[] field = null, SortDefinition sort = null) { try { //不指定查询字段 if (field == null || field.Length == 0) { if (filter == null) { if (sort == null) return await _collection.Find(_ => true).ToListAsync(); //进行排序 return await _collection.Find(_ => true).Sort(sort).ToListAsync(); } if (sort == null) return await _collection.Find(filter).ToListAsync(); //进行排序 return await _collection.Find(filter).Sort(sort).ToListAsync(); } #region 指定查询字段 //指定查询字段 var fieldList = new List>(); for (int i = 0; i < field.Length; i++) { fieldList.Add(Builders.Projection.Include(field[i].ToString())); } var projection = Builders.Projection.Combine(fieldList); fieldList?.Clear(); if (sort == null) return await _collection.Find(filter).Project(projection).ToListAsync(); //排序查询 return await _collection.Find(filter).Sort(sort).Project(projection).ToListAsync(); #endregion } catch (Exception ex) { _logger.LogError(ex.ToString()); throw ex; } } /// /// 查询所有数据 /// /// public async Task> GetAll() { try { return await _collection.Find(_ => true).ToListAsync(); } catch (Exception ex) { _logger.LogError(ex.ToString()); throw ex; } } /// /// 分页查询数据列表 /// /// /// /// /// /// public async Task> GetByPage(FilterDefinition filter, int pageIndex, int pageSize, SortDefinition sort = null) { try { //没有查询条件 if (filter == null) { if (sort == null) return await _collection.Find(_ => true).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); //排序 return await _collection.Find(_ => true).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); } if (sort == null) return await _collection.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); //排序 return await _collection.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); } catch (Exception ex) { _logger.LogError(ex.ToString()); throw ex; } } /// /// 查询一条数据 /// /// /// public async Task GetSingle(TKey key) { var filter = Builders.Filter.Eq("id", key); try { return await _collection.Find(filter).FirstOrDefaultAsync(); } catch (Exception ex) { _logger.LogError(ex.ToString()); throw ex; } } /// /// 根据查询条件查出 /// /// /// public async Task GetSingle(Expression> @where = null) { try { return await _collection.Find(@where).FirstOrDefaultAsync(); } catch (Exception ex) { _logger.LogError(ex.ToString()); throw ex; } } /// /// 查询一条数据 条件 排序 /// /// /// public async Task GetSingle(Expression> @where = null, SortDefinition sort = null) { try { if (sort == null) return await _collection.Find(@where).FirstOrDefaultAsync(); return await _collection.Find(@where).Sort(sort).FirstOrDefaultAsync(); } catch (Exception ex) { _logger.LogError(ex.ToString()); throw ex; } } /// /// 删除一项 根据id /// /// /// public async Task Remove(TKey key) { try { DeleteResult actionResult = await _collection.DeleteOneAsync(Builders.Filter.Eq("id", key)); return actionResult.IsAcknowledged && actionResult.DeletedCount > 0; } catch (Exception ex) { _logger.LogError(ex.ToString()); throw ex; } } /// /// 依据条件删除多项 /// /// /// public async Task Remove(Expression> @where = null) { try { DeleteResult actionResult = await _collection.DeleteManyAsync(@where); return actionResult.IsAcknowledged && actionResult.DeletedCount > 0; } catch (Exception ex) { _logger.LogError(ex.ToString()); throw ex; } } /// /// 删除所有数据 /// /// public async Task RemoveAll() { try { DeleteResult actionResult = await _collection.DeleteManyAsync(new BsonDocument()); return actionResult.IsAcknowledged && actionResult.DeletedCount > 0; } catch (Exception ex) { _logger.LogError(ex.ToString()); return false; } } /// /// 修改数据 /// /// /// public async Task Update(T entity) { try { //修改条件 FilterDefinition filter = Builders.Filter.Eq("id", entity.id); //要修改的字段 var list = new List>(); foreach (var item in entity.GetType().GetProperties()) { if (item.Name.ToLower() == "id") continue; list.Add(Builders.Update.Set(item.Name, item.GetValue(entity))); } var updatefilter = Builders.Update.Combine(list); var r = await _collection.UpdateOneAsync(filter, updatefilter, null); //return r.IsAcknowledged && r.ModifiedCount > 0; return r.IsAcknowledged ; } catch (Exception ex) { _logger.LogError(ex.ToString()); return false; } } public async Task Update(string id, Dictionary dic) { try { //修改条件 FilterDefinition filter = Builders.Filter.Eq("_id", new ObjectId(id)); //要修改的字段 var list = new List>(); foreach (var item in dic) { list.Add(Builders.Update.Set(item.Key.ToString(), item.Value)); } var updatefilter = Builders.Update.Combine(list); var r = await _collection.UpdateOneAsync(filter, updatefilter, null); //return r.IsAcknowledged && r.ModifiedCount > 0; return r.IsAcknowledged; } catch (Exception ex) { _logger.LogError(ex.ToString()); return false; } } public async Task UpdateOne(T entity) { try { //修改条件 FilterDefinition filter = Builders.Filter.Eq("id", entity.id); var query = await _collection.Find(filter).FirstOrDefaultAsync(); //要修改的字段 var list = new List>(); //要删除的字段 var dellist = new List>(); foreach (var property in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)) { //非空的复杂类型 if (property.PropertyType.IsClass && property.PropertyType != typeof(string) && property.GetValue(entity) != null) { var subarray = property.PropertyType.GetProperties(BindingFlags.Instance | BindingFlags.Public); if (typeof(IList).IsAssignableFrom(property.PropertyType)) { #region 集合类型 foreach (var sub in subarray) { //if (sub.PropertyType.IsClass && sub.PropertyType != typeof(string)) if (sub.PropertyType.IsClass) { //var arr = property.GetValue(entity) as IList; //var arrold = property.GetValue(query) as IList; var enumobj = property.GetValue(entity) as IEnumerable; //var enumoldobj = property.GetValue(query) as IEnumerable; dellist.Add(Builders.Update.Unset(property.Name)); list.Add(Builders.Update.PushEach(property.Name, enumobj)); //if (sub.PropertyType != typeof(string)) //{ // var subinnerarray = sub.PropertyType.GetProperties(BindingFlags.Instance | BindingFlags.Public); // if (arr != null && arr.Count > 0) // { // for (int s = 0; s < arr.Count; s++) // { // foreach (var subInner in subinnerarray) // { // //propertyName.index.innerPropertyName // list.Add(Builders.Update.Set(property.Name + "." + s + "." + subInner.Name, subInner.GetValue(arr[s]))); // } // } // } // int n = 0; // if (arr != null) { n = arr.Count; } // int o = 0; // if (arrold != null) { o = arrold.Count; } // if (o > n) // { // for (int i = n; i < arrold.Count; i++) // { // switch (sub.PropertyType.Name) // { // case "ExtensionModel": // FilterDefinition subfilterexten = Builders.Filter.Eq(subinnerarray[0].Name, subinnerarray[0].GetValue(arrold[i])); // dellist.Add(Builders.Update.PullFilter(property.Name, subfilterexten)); // break; // case "FileBaseModel": // FilterDefinition subfilterfile = Builders.Filter.Eq(subinnerarray[0].Name, subinnerarray[0].GetValue(arrold[i])); // dellist.Add(Builders.Update.PullFilter(property.Name, subfilterfile)); // break; // case "MaterialModel": // FilterDefinition subfiltermater = Builders.Filter.Eq(subinnerarray[0].Name, subinnerarray[0].GetValue(arrold[i])); // dellist.Add(Builders.Update.PullFilter(property.Name, subfiltermater)); // break; // } // } // } //} //else //{ // dellist.Add(Builders.Update.PullAll(property.Name, enumoldobj)); // list.Add(Builders.Update.PushEach(property.Name, enumobj)); //} } } #endregion } else { #region 实体类型 //复杂类型,导航属性,类对象和集合对象 foreach (var sub in subarray) { list.Add(Builders.Update.Set(property.Name + "." + sub.Name, sub.GetValue(property.GetValue(entity)))); } #endregion } } else { if (property.Name.ToLower() != "id")//更新集中不能有实体键_id { list.Add(Builders.Update.Set(property.Name, property.GetValue(entity))); } } } if (dellist.Count > 0) { var delfilter = Builders.Update.Combine(dellist); var d = await _collection.UpdateOneAsync(filter, delfilter, null); } var updatefilter = Builders.Update.Combine(list); var r = await _collection.UpdateOneAsync(filter, updatefilter, null); //return r.IsAcknowledged && r.ModifiedCount > 0; return r.IsAcknowledged; } catch (Exception ex) { _logger.LogError(ex.ToString()); return false; } } /// /// 批量修改数据 /// public async Task UpdateManay(T entity, Dictionary dic, FilterDefinition filter = null) { try { //要修改的字段 var list = new List>(); foreach (var item in entity.GetType().GetProperties()) { if (!dic.ContainsKey(item.Name)) continue; var value = dic[item.Name]; list.Add(Builders.Update.Set(item.Name, value)); } var updatefilter = Builders.Update.Combine(list); var r = await _collection.UpdateManyAsync(filter, updatefilter); return r.IsAcknowledged && r.ModifiedCount > 0; } catch (Exception ex) { _logger.LogError(ex.ToString()); return false; } } /// /// 异步根据条件获取总数 /// /// 条件 /// public async Task CountAsync(FilterDefinition filter = null) { try { return await _collection.CountAsync(filter == null ? FilterDefinition.Empty : filter); } catch (Exception ex) { _logger.LogError(ex.ToString()); return 0; } } /// /// 异步添加一条数据并返回ID /// /// /// public async Task AddRetID(T entity) { try { await _collection.InsertOneAsync(entity); return entity.id.ToString(); } catch (Exception ex) { _logger.LogError(ex.ToString()); return null; } } } }