/// <summary> /// 构造函数 /// </summary> /// <param name="baseDbContext">BaseDbContext</param> public GenericDbAccessor(GenericDbContext baseDbContext) { _db = baseDbContext; _provider = DbFactory.GetProvider(DbType); }
public async Task <List <T> > ToListAsync() { //去除分页,获取前Take+Skip数量 int?take = _source.GetTakeCount(); int?skip = _source.GetSkipCount(); skip = skip == null ? 0 : skip; var(sortColumn, sortType) = _source.GetOrderBy(); var noPaginSource = _source.RemoveTake().RemoveSkip(); if (!take.IsNullOrEmpty()) { noPaginSource = noPaginSource.Take(take.Value + skip.Value); } //从各个分表获取数据 var tables = ShardingConfig.ConfigProvider.GetReadTables(_absTableName, _absDbName, _source); SynchronizedCollection <IDbAccessor> dbs = new SynchronizedCollection <IDbAccessor>(); List <Task <List <T> > > tasks = tables.Select(aTable => { var targetTable = MapTable(aTable.tableName); IDbAccessor db; if (_repository.OpenedTransaction) { db = _repository.GetMapDbAccessor(aTable.conString, aTable.dbType); } else { db = DbFactory.GetDbAccessor(aTable.conString, aTable.dbType); } dbs.Add(db); var targetIQ = db.GetIQueryable(targetTable); var newQ = noPaginSource.ChangeSource(targetIQ); return(newQ .Cast <object>() .Select(x => x.ChangeType <T>()) .ToListAsync()); }).ToList(); List <T> all = new List <T>(); (await Task.WhenAll(tasks.ToArray())).ToList().ForEach(x => all.AddRange(x)); if (!_repository.OpenedTransaction) { dbs.ForEach(x => x.Dispose()); } //合并数据 var resList = all; if (!sortColumn.IsNullOrEmpty() && !sortType.IsNullOrEmpty()) { resList = resList.AsQueryable().OrderBy($"{sortColumn} {sortType}").ToList(); } if (!skip.IsNullOrEmpty()) { resList = resList.Skip(skip.Value).ToList(); } if (!take.IsNullOrEmpty()) { resList = resList.Take(take.Value).ToList(); } return(resList); }
/// <summary> /// 构造函数 /// </summary> /// <param name="baseDbContext">BaseDbContext</param> public AbstractDbAccessor(BaseDbContext baseDbContext) { _db = baseDbContext; _provider = DbFactory.GetProvider(DbType); }
/// <summary> /// 转为Sharding /// </summary> /// <typeparam name="T">实体泛型</typeparam> /// <param name="source">数据源</param> /// <param name="absDbName">抽象数据库</param> /// <returns>IShardingQueryable</returns> public static IShardingQueryable <T> ToSharding <T>(this IQueryable <T> source, string absDbName = ShardingConfig.DefaultAbsDbName) where T : class, new() { ShardingConfig.CheckInit(); return(new ShardingQueryable <T>(source, DbFactory.GetShardingDbAccessor(absDbName) as ShardingDbAccessor, absDbName)); }