From 1a9d3380df391d2ae59b7cd9318f7dd39dc78238 Mon Sep 17 00:00:00 2001 From: hanzhiyuan Date: Wed, 15 May 2024 17:57:43 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MySqlRepositoryBase.cs | 8 +- .../SqlServerRepositoryBase.cs | 8 +- src/NuClear.Dapper.UnitTest/TestOrder.cs | 8 +- src/NuClear.Dapper/BaseEntity.cs | 120 +----------------- src/NuClear.Dapper/BaseEntityWithLongKey.cs | 14 ++ src/NuClear.Dapper/Context/ContextBase.cs | 20 ++- src/NuClear.Dapper/Context/IContext.cs | 7 +- .../Extensions/SqlParameterExtensions.cs | 2 +- src/NuClear.Dapper/IEntity.cs | 13 +- src/NuClear.Dapper/IRepository.cs | 19 ++- src/NuClear.Dapper/ISearch.cs | 12 ++ src/NuClear.Dapper/Pager.cs | 16 ++- src/NuClear.Dapper/QueryObject/ISearch.cs | 13 -- src/NuClear.Dapper/QueryObject/Query.cs | 4 +- src/NuClear.Dapper/RepositoryBase.cs | 39 +++--- src/NuClear.Dapper/Sort.cs | 5 +- .../Scripting/ChooseNodeHandler.cs | 6 +- .../Scripting/XElementExtensions.cs | 14 +- .../UnitOfWork/IUnitOfWorkCompleteHandle.cs | 4 - src/NuClear.Dapper/UnitOfWork/UnitOfWork.cs | 57 +-------- .../UnitOfWork/UnitOfWorkCompleteHandle.cs | 38 +----- .../Utility/BatchFuncUtility.cs | 29 ++++- 22 files changed, 159 insertions(+), 297 deletions(-) create mode 100644 src/NuClear.Dapper/BaseEntityWithLongKey.cs create mode 100644 src/NuClear.Dapper/ISearch.cs delete mode 100644 src/NuClear.Dapper/QueryObject/ISearch.cs diff --git a/src/NuClear.Dapper.MySql/MySqlRepositoryBase.cs b/src/NuClear.Dapper.MySql/MySqlRepositoryBase.cs index 588010a..5c15d01 100644 --- a/src/NuClear.Dapper.MySql/MySqlRepositoryBase.cs +++ b/src/NuClear.Dapper.MySql/MySqlRepositoryBase.cs @@ -3,11 +3,15 @@ namespace NuClear.Dapper.MySql { - public abstract class MySqlRepositoryBase : RepositoryBase - where T : IEntity + public abstract class MySqlRepositoryBase : RepositoryBase + where TEntity : IEntity { protected override IAggrQuerySqlParser AggrQuerySqlParser => new MySqlAggrQuerySqlParser(); protected override ICriterionSqlParser CriterionSqlParser => new MySqlCriterionSqlParser(); protected override ISqlParser SqlParser => new MySqlSqlParser(); } + public abstract class MySqlRepositoryBaseWithLongKey : MySqlRepositoryBase + where TEntity : IEntityWithLongKey + { + } } diff --git a/src/NuClear.Dapper.SqlServer/SqlServerRepositoryBase.cs b/src/NuClear.Dapper.SqlServer/SqlServerRepositoryBase.cs index 25a36ca..9105ec8 100644 --- a/src/NuClear.Dapper.SqlServer/SqlServerRepositoryBase.cs +++ b/src/NuClear.Dapper.SqlServer/SqlServerRepositoryBase.cs @@ -3,11 +3,15 @@ namespace NuClear.Dapper.SqlServer { - public abstract class SqlServerRepositoryBase : RepositoryBase - where T : IEntity + public abstract class SqlServerRepositoryBase : RepositoryBase + where TEntity : IEntity { protected override IAggrQuerySqlParser AggrQuerySqlParser => new SqlServerAggrQuerySqlParser(); protected override ICriterionSqlParser CriterionSqlParser => new SqlServerCriterionSqlParser(); protected override ISqlParser SqlParser => new SqlServerSqlParser(); } + public abstract class SqlServerRepositoryBaseWithLongKey : SqlServerRepositoryBase + where TEntity : IEntityWithLongKey + { + } } diff --git a/src/NuClear.Dapper.UnitTest/TestOrder.cs b/src/NuClear.Dapper.UnitTest/TestOrder.cs index 8590389..8c57fec 100644 --- a/src/NuClear.Dapper.UnitTest/TestOrder.cs +++ b/src/NuClear.Dapper.UnitTest/TestOrder.cs @@ -1,11 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace NuClear.Dapper.UnitTest +namespace NuClear.Dapper.UnitTest { public class TestOrder : IEntity { - public string Id { get; set; } + public long Id { get; set; } } } diff --git a/src/NuClear.Dapper/BaseEntity.cs b/src/NuClear.Dapper/BaseEntity.cs index 30e6565..fb9580f 100644 --- a/src/NuClear.Dapper/BaseEntity.cs +++ b/src/NuClear.Dapper/BaseEntity.cs @@ -1,35 +1,11 @@ -using NuClear.Snowflake; -using System; +using System; namespace NuClear.Dapper { /// /// 所有实体的基类 /// - public class BaseEntity : IEntity - { - public BaseEntity() - { - Id = Guid.NewGuid().ToString("N"); - - CreateTime = DateTime.Now; - LastUpdateTime = DateTime.Now; - } - - public string Id { get; set; } - - /// - /// 数据的创建时间 - /// - public DateTime CreateTime { get; set; } - - /// - /// 最后更新时间 - /// - public DateTime LastUpdateTime { get; set; } - } - - public class BaseEntity : IEntity + public class BaseEntity : IEntity { public BaseEntity() { @@ -37,50 +13,9 @@ public BaseEntity() LastUpdateTime = DateTime.Now; } - public T Id { get; set; } - - /// - /// 数据的创建时间 - /// - public DateTime CreateTime { get; set; } - - /// - /// 最后更新时间 - /// - public DateTime LastUpdateTime { get; set; } - string IEntity.Id - { - get - { - return this.Id.ToString(); - } - set - { - T ret = (T)Convert.ChangeType("-1", typeof(T)); - - try - { - ret = (T)Convert.ChangeType(value, typeof(T)); - } - catch { } - - this.Id = ret; - } - } - } - - public class BaseEntityNum : IEntity - { - public BaseEntityNum() - { - Id = IdGenerator.NextId(); - CreateTime = DateTime.Now; - LastUpdateTime = DateTime.Now; - } + public TKey Id { get; set; } - public long Id { get; set; } - string IEntity.Id { get => Id.ToString(); set => Convert.ToUInt64(Id); } /// /// 数据的创建时间 /// @@ -91,53 +26,4 @@ public BaseEntityNum() /// public DateTime LastUpdateTime { get; set; } } - - public class BaseEntityMySql : IEntity - { - public BaseEntityMySql() - { - Id = IdGenerator.NextId(); - - CreateTimeTxt = DateTime.Now; - CreateTime = CreateTimeTxt.ToTimeStamp(); - LastUpdateTimeTxt = DateTime.Now; - LastUpdateTime = LastUpdateTimeTxt.ToTimeStamp(); - } - - public long Id { get; set; } - string IEntity.Id { get => Id.ToString(); set => Convert.ToUInt64(Id); } - /// - /// 数据的创建时间 - /// - public DateTime CreateTimeTxt { get; set; } - public long CreateTime { get; set; } - - - /// - /// 最后更新时间 - /// - public DateTime LastUpdateTimeTxt { get; set; } - public long LastUpdateTime { get; set; } - } - - public static class IdGenerator - { - private static IdWorker idWorker = new IdWorker(1, 1); - - public static long NextId() - { - return idWorker.NextId(); - } - - public static long ToTimeStamp(this DateTime time) - { - DateTime startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), - TimeZoneInfo.Local); - long stamp = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 - return stamp; - } - } - - - } \ No newline at end of file diff --git a/src/NuClear.Dapper/BaseEntityWithLongKey.cs b/src/NuClear.Dapper/BaseEntityWithLongKey.cs new file mode 100644 index 0000000..4052835 --- /dev/null +++ b/src/NuClear.Dapper/BaseEntityWithLongKey.cs @@ -0,0 +1,14 @@ +using NuClear.Snowflake; + +namespace NuClear.Dapper +{ + public class BaseEntityWithLongKey : BaseEntity, IEntity + { + internal static readonly IdWorker idWorker = IdWorker.Create(); + public BaseEntityWithLongKey() + : base() + { + Id = idWorker.NextId(); + } + } +} \ No newline at end of file diff --git a/src/NuClear.Dapper/Context/ContextBase.cs b/src/NuClear.Dapper/Context/ContextBase.cs index cdb501a..a8741f0 100644 --- a/src/NuClear.Dapper/Context/ContextBase.cs +++ b/src/NuClear.Dapper/Context/ContextBase.cs @@ -30,8 +30,6 @@ public IDbTransaction Transaction get { return _transaction; } } - - protected abstract void CreateConnection(); protected ContextBase() @@ -53,8 +51,7 @@ public void BeginTransaction() if (_isTransactionStarted) throw new InvalidOperationException("已开启事务."); - if (_connection.State == ConnectionState.Closed) - _connection.Open(); + EnsureOpenConnection(); _transaction = _connection.BeginTransaction(); @@ -63,6 +60,14 @@ public void BeginTransaction() DebugPrint("事务开启."); } + private void EnsureOpenConnection() + { + if (_connection.State == ConnectionState.Closed) + { + _connection.Open(); + } + } + public void Commit() { if (!_isTransactionStarted) @@ -80,7 +85,9 @@ public void Commit() public void Rollback() { if (!_isTransactionStarted) + { throw new InvalidOperationException("当前无事务."); + } _transaction.Rollback(); _transaction.Dispose(); @@ -99,7 +106,10 @@ protected virtual void Dispose(bool disposing) { if (_isTransactionStarted) { - try { Rollback(); } + try + { + Rollback(); + } catch { DebugPrint("事务已开启,释放数据库连接回滚."); diff --git a/src/NuClear.Dapper/Context/IContext.cs b/src/NuClear.Dapper/Context/IContext.cs index c81df87..78d1cdc 100644 --- a/src/NuClear.Dapper/Context/IContext.cs +++ b/src/NuClear.Dapper/Context/IContext.cs @@ -5,16 +5,21 @@ namespace NuClear.Dapper.Context { public interface IContext : IDisposable { - + /// + /// Id + /// string Id { get; } + /// /// 数据库连接 /// IDbConnection Connection { get; } + /// /// 数据库事务 /// IDbTransaction Transaction { get; } + /// /// 是否已开启事务 /// diff --git a/src/NuClear.Dapper/Extensions/SqlParameterExtensions.cs b/src/NuClear.Dapper/Extensions/SqlParameterExtensions.cs index f9e8575..7cef8b5 100644 --- a/src/NuClear.Dapper/Extensions/SqlParameterExtensions.cs +++ b/src/NuClear.Dapper/Extensions/SqlParameterExtensions.cs @@ -13,7 +13,7 @@ public static object ToDynamicObject(this List parameters) { dic.Add(item.ParameterName, item.Value); } - return obj as object; + return obj; } } } diff --git a/src/NuClear.Dapper/IEntity.cs b/src/NuClear.Dapper/IEntity.cs index 3134255..1217229 100644 --- a/src/NuClear.Dapper/IEntity.cs +++ b/src/NuClear.Dapper/IEntity.cs @@ -5,17 +5,18 @@ /// public interface IEntity { - /// - /// 主键 - /// - string Id { get; set; } } - public interface IEntity + public interface IEntityWithLongKey : IEntity + { + + } + + public interface IEntity : IEntity { /// /// 主键 /// - T Id { get; set; } + TKey Id { get; set; } } } \ No newline at end of file diff --git a/src/NuClear.Dapper/IRepository.cs b/src/NuClear.Dapper/IRepository.cs index 8965ead..a4abe12 100644 --- a/src/NuClear.Dapper/IRepository.cs +++ b/src/NuClear.Dapper/IRepository.cs @@ -7,9 +7,10 @@ namespace NuClear.Dapper { - public interface IRepository : IDisposable where TEntity : IEntity + public interface IRepository : IDisposable + where TEntity : IEntity { - TEntity FirstOrDefault(string id); + TEntity FirstOrDefault(TKey id); TEntity FirstOrDefault(Query query, Sort sort = null); @@ -21,7 +22,7 @@ public interface IRepository : IDisposable where TEntity : IEntity /// /// int Count(Query query); - bool Exists(string id); + bool Exists(TKey id); bool Exists(Query query); IEnumerable Query(Query query, Sort sort = null); IEnumerable Query(string query, object parameters = null); @@ -38,19 +39,17 @@ public interface IRepository : IDisposable where TEntity : IEntity IEnumerable Query(string sql, Func map, object param = null, string split = null) where TReturn : class; IEnumerable Query(string sql, Func map, object param = null, string split = null) where TReturn : class; - - void Insert(TEntity entity); void InsertBatch(IEnumerable entities); int Execute(string sql, object parameters = null, CommandType? commandType = null); - void Delete(string id); + void Delete(TKey id); void Delete(TEntity entity); - void DeleteBatch(params string[] ids); + void DeleteBatch(params TKey[] ids); void DeleteBatch(IEnumerable entities); void Update(TEntity entity); void UpdateBatch(IEnumerable entities); - Task FirstOrDefaultAsync(string id); + Task FirstOrDefaultAsync(TKey id); Task FirstOrDefaultAsync(Query query, Sort sort = null); @@ -62,7 +61,7 @@ public interface IRepository : IDisposable where TEntity : IEntity /// /// Task CountAsync(Query query); - Task ExistsAsync(string id); + Task ExistsAsync(TKey id); Task ExistsAsync(Query query); Task> QueryAsync(Query query, Sort sort = null); Task> QueryAsync(string query, object parameters = null); @@ -77,7 +76,7 @@ public interface IRepository : IDisposable where TEntity : IEntity Task<(IEnumerable, int)> QueryPagedAsync(string countSql, object countParameters, string query, object parameters) where TAny : class; Task InsertAsync(TEntity entity); Task ExecuteAsync(string sql, object parameters = null, CommandType? commandType = null); - Task DeleteAsync(string id); + Task DeleteAsync(TKey id); Task DeleteAsync(TEntity entity); Task UpdateAsync(TEntity entity); diff --git a/src/NuClear.Dapper/ISearch.cs b/src/NuClear.Dapper/ISearch.cs new file mode 100644 index 0000000..32188a6 --- /dev/null +++ b/src/NuClear.Dapper/ISearch.cs @@ -0,0 +1,12 @@ +using NuClear.Dapper.QueryObject; + +namespace NuClear.Dapper +{ + /// + /// 查询对象 + /// + public interface ISearch + { + Query CreateQuery(); + } +} diff --git a/src/NuClear.Dapper/Pager.cs b/src/NuClear.Dapper/Pager.cs index b34417e..8f4bf74 100644 --- a/src/NuClear.Dapper/Pager.cs +++ b/src/NuClear.Dapper/Pager.cs @@ -9,14 +9,28 @@ public Pager() this.PageIndex = 1; this.IsGetTotalCount = true; } - + /// + /// 总记录数 + /// public virtual int TotalCount { get; set; } + /// + /// 总页数 + /// public virtual int PageCount { get { if (this.PageSize >= 0) { return (this.TotalCount - 1) / this.PageSize + 1; } return 1; } } + /// + /// 每页数量 + /// public virtual int PageSize { get; set; } + /// + /// 页码 + /// public virtual int PageIndex { get; set; } + /// + /// 是否获取总记录数 + /// public bool IsGetTotalCount { get; set; } } diff --git a/src/NuClear.Dapper/QueryObject/ISearch.cs b/src/NuClear.Dapper/QueryObject/ISearch.cs deleted file mode 100644 index 014430d..0000000 --- a/src/NuClear.Dapper/QueryObject/ISearch.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NuClear.Dapper.QueryObject -{ - public interface ISearch - { - Query CreateQuery(); - } -} diff --git a/src/NuClear.Dapper/QueryObject/Query.cs b/src/NuClear.Dapper/QueryObject/Query.cs index 8e27a1c..7eeb6d0 100644 --- a/src/NuClear.Dapper/QueryObject/Query.cs +++ b/src/NuClear.Dapper/QueryObject/Query.cs @@ -33,10 +33,12 @@ public Query AddSubQuery(Query subQuery) subQueries.Add(subQuery); return this; } + internal void HandleRepeatProperty() { var criterions = GetAllCriterions(); - var repeatProperties = criterions.Where(x => x.Operator != CriteriaOperator.None).GroupBy(c => c.PropertyName.ToLower()) + var repeatProperties = criterions.Where(x => x.Operator != CriteriaOperator.None) + .GroupBy(c => c.PropertyName.ToLower()) .Where(c => c.Count() > 1) .Select(c => new { PropertyName = c.Key, Count = c.Count() }).ToArray(); diff --git a/src/NuClear.Dapper/RepositoryBase.cs b/src/NuClear.Dapper/RepositoryBase.cs index 88b1ae7..e737620 100644 --- a/src/NuClear.Dapper/RepositoryBase.cs +++ b/src/NuClear.Dapper/RepositoryBase.cs @@ -11,7 +11,8 @@ namespace NuClear.Dapper { - public abstract class RepositoryBase : IRepository where TEntity : IEntity + public abstract class RepositoryBase : IRepository + where TEntity : IEntity { protected const int Default_CommandTimeout = 360; protected abstract IContext Context { get; } @@ -89,7 +90,7 @@ protected async Task> InternalQueryAsync(sql, param).FirstOrDefault(); } - public virtual async Task FirstOrDefaultAsync(string id) + public virtual async Task FirstOrDefaultAsync(TKey id) { var query = QueryObject.Query.Create() .Add(Criterion.Create("Id", id, CriteriaOperator.Equal, this.TableAliasName)); @@ -123,14 +124,16 @@ public virtual async Task FirstOrDefaultAsync(string id) public virtual async Task FirstOrDefaultAsync(Query query, Sort sort = null) { var whereSql = GetWhereSql(query, out object param); + var sortSql = sort?.Translate(); - return await this.QueryFirstOrDefaultAsync(this.SqlParser.CreateTop1SelectSql(SelectSql, whereSql, - sort?.Translate()), param); + var top1Sql = this.SqlParser.CreateTop1SelectSql(SelectSql, whereSql, sortSql); + + return await this.InternalQueryFirstOrDefaultAsync(top1Sql, param); } - private async Task QueryFirstOrDefaultAsync(string query, object parameters = null, bool recompile = false) + private async Task InternalQueryFirstOrDefaultAsync(string query, object parameters = null) { - return await Conn.QueryFirstOrDefaultAsync(query + GetRecompileSql(recompile), parameters, Tran, commandTimeout: Default_CommandTimeout); + return await Conn.QueryFirstOrDefaultAsync(query, parameters, Tran, commandTimeout: Default_CommandTimeout); } #endregion @@ -162,7 +165,7 @@ public virtual async Task CountAsync(Query query) #region Exists - public virtual bool Exists(string id) + public virtual bool Exists(TKey id) { var query = QueryObject.Query.Create().Add(Criterion.Create("Id", id, CriteriaOperator.Equal, this.TableAliasName)); if (typeof(IDeleted).IsAssignableFrom(typeof(TEntity))) @@ -180,7 +183,7 @@ public virtual bool Exists(Query query) return this.Count(query) > 0; } - public virtual async Task ExistsAsync(string id) + public virtual async Task ExistsAsync(TKey id) { var query = QueryObject.Query.Create().Add(Criterion.Create("Id", id, CriteriaOperator.Equal, this.TableAliasName)); if (typeof(IDeleted).IsAssignableFrom(typeof(TEntity))) @@ -633,11 +636,11 @@ public virtual void Delete(TEntity entity) { Execute(DeleteSql, new { entity.Id }); } - public virtual void Delete(string id) + public virtual void Delete(TKey id) { Execute(DeleteSql, new { Id = id }); } - public virtual void DeleteBatch(params string[] ids) + public virtual void DeleteBatch(params TKey[] ids) { foreach (var id in ids) { @@ -656,7 +659,7 @@ public virtual async Task DeleteAsync(TEntity entity) await ExecuteAsync(DeleteSql, new { entity.Id }); } - public virtual async Task DeleteAsync(string id) + public virtual async Task DeleteAsync(TKey id) { await ExecuteAsync(DeleteSql, new { Id = id }); } @@ -685,10 +688,16 @@ public void Dispose() #region Sql public virtual string TableAliasName { get { return ""; } } - public virtual string SelectSql { get { return SqlResource.Select; } } - public virtual string InsertSql { get { return SqlResource.Insert; } } - public virtual string UpdateSql { get { return SqlResource.Update; } } + public virtual string SelectSql { get { return SqlResource.Select; } } + public virtual string InsertSql { get { return SqlResource.Insert; } } + public virtual string UpdateSql { get { return SqlResource.Update; } } public virtual string DeleteSql { get { return SqlResource.Delete; } } #endregion } + + public abstract class RepositoryBaseWithLongKey : RepositoryBase + where TEntity : IEntityWithLongKey + { + } + } diff --git a/src/NuClear.Dapper/Sort.cs b/src/NuClear.Dapper/Sort.cs index 5ca6301..c253896 100644 --- a/src/NuClear.Dapper/Sort.cs +++ b/src/NuClear.Dapper/Sort.cs @@ -5,12 +5,13 @@ namespace NuClear.Dapper { public class Sort { - public static Sort DefaultSort { get { return new Sort().Add(SortCondition.Create("CreateTime", false)); } } + private readonly List _sort = new List(); private Sort() { } - private readonly List _sort = new List(); + public static Sort DefaultSort { get { return new Sort().Add(SortCondition.Create("CreateTime", false)); } } + public IEnumerable Sorts { get { return this._sort; } } public Sort Add(SortCondition sortCondition) diff --git a/src/NuClear.Dapper/SqlResources/Scripting/ChooseNodeHandler.cs b/src/NuClear.Dapper/SqlResources/Scripting/ChooseNodeHandler.cs index f169326..5efa057 100644 --- a/src/NuClear.Dapper/SqlResources/Scripting/ChooseNodeHandler.cs +++ b/src/NuClear.Dapper/SqlResources/Scripting/ChooseNodeHandler.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; +using NuClear.Dapper.Exceptions; +using System.Collections.Generic; using System.Linq; using System.Xml.Linq; -using NuClear.Dapper.Exceptions; namespace NuClear.Dapper.SqlResources.Scripting { @@ -48,7 +48,5 @@ private ISqlNode GetDefaultSqlNode(List defaultSqlNodes) } return defaultSqlNode; } - - } } diff --git a/src/NuClear.Dapper/SqlResources/Scripting/XElementExtensions.cs b/src/NuClear.Dapper/SqlResources/Scripting/XElementExtensions.cs index 7ccb168..f39ed26 100644 --- a/src/NuClear.Dapper/SqlResources/Scripting/XElementExtensions.cs +++ b/src/NuClear.Dapper/SqlResources/Scripting/XElementExtensions.cs @@ -1,9 +1,7 @@ -using System; +using NuClear.Dapper.Exceptions; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Xml.Linq; -using NuClear.Dapper.Exceptions; namespace NuClear.Dapper.SqlResources.Scripting { @@ -27,10 +25,6 @@ private static void InitNodeHandlerMap() _nodeHandlerMap.Add("choose", new ChooseNodeHandler()); _nodeHandlerMap.Add("otherwise", new OtherwiseNodeHandler()); _nodeHandlerMap.Add("when", new IfNodeHandler()); - - //_nodeHandlerMap.Add("trim", new TrimHandler()); - //_nodeHandlerMap.Add("where", new WhereHandler()); - //_nodeHandlerMap.Add("set", new SetHandler()); } public static MixedSqlNode ParseDynamicTags(this XElement node) @@ -50,11 +44,7 @@ public static MixedSqlNode ParseDynamicTags(this XElement node) { var elementNode = XElement.Parse(child.ToString()); var nodeName = elementNode.Name.ToString(); - INodeHandler handler = GetNodeHandler(nodeName); - if (handler == null) - { - throw new SqlParseException($"不识别的ElementName:{ nodeName }!"); - } + INodeHandler handler = GetNodeHandler(nodeName) ?? throw new SqlParseException($"不识别的ElementName:{nodeName}!"); handler.HandleNode(elementNode, contents); } } diff --git a/src/NuClear.Dapper/UnitOfWork/IUnitOfWorkCompleteHandle.cs b/src/NuClear.Dapper/UnitOfWork/IUnitOfWorkCompleteHandle.cs index 4f43efa..92ec764 100644 --- a/src/NuClear.Dapper/UnitOfWork/IUnitOfWorkCompleteHandle.cs +++ b/src/NuClear.Dapper/UnitOfWork/IUnitOfWorkCompleteHandle.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NuClear.Dapper { diff --git a/src/NuClear.Dapper/UnitOfWork/UnitOfWork.cs b/src/NuClear.Dapper/UnitOfWork/UnitOfWork.cs index 9014cc0..61aa68b 100644 --- a/src/NuClear.Dapper/UnitOfWork/UnitOfWork.cs +++ b/src/NuClear.Dapper/UnitOfWork/UnitOfWork.cs @@ -61,63 +61,10 @@ public void Dispose() #endregion } - public class UnitOfWork : IUnitOfWork + public class UnitOfWork : UnitOfWork, IUnitOfWork, IUnitOfWork { - internal readonly IContext _context; - public UnitOfWork(IContext context) + public UnitOfWork(IContext context) : base(context) { - this._context = context; - } - - public IContext Context { get { return _context; } } - - public IUnitOfWorkCompleteHandle Begin() - { - if (_context.IsTransactionStarted) - { - throw new InvalidOperationException("已开启事务."); - } - _context.BeginTransaction(); - System.Console.WriteLine($"===========> 事务已开启, {_context.Id}"); - return new UnitOfWorkCompleteHandle(this); - } - public void Commit() - { - if (!_context.IsTransactionStarted) - throw new InvalidOperationException("事务已提交或被释放."); - - _context.Commit(); - System.Console.WriteLine($"===========> 事务已提交, {_context.Id}"); - } - public void Rollback() - { - if (!_context.IsTransactionStarted) - throw new InvalidOperationException("当前无事务."); - _context.Rollback(); - System.Console.WriteLine($"===========> 事务已回滚, {_context.Id}"); } - - #region IDisposed - - private bool disposed = false; - - protected virtual void Dispose(bool disposing) - { - if (!this.disposed) - { - if (disposing) - { - _context.Dispose(); - } - } - this.disposed = true; - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - #endregion } } diff --git a/src/NuClear.Dapper/UnitOfWork/UnitOfWorkCompleteHandle.cs b/src/NuClear.Dapper/UnitOfWork/UnitOfWorkCompleteHandle.cs index af92559..644bc19 100644 --- a/src/NuClear.Dapper/UnitOfWork/UnitOfWorkCompleteHandle.cs +++ b/src/NuClear.Dapper/UnitOfWork/UnitOfWorkCompleteHandle.cs @@ -1,5 +1,5 @@ -using System; -using NuClear.Dapper.Context; +using NuClear.Dapper.Context; +using System; namespace NuClear.Dapper { @@ -43,41 +43,11 @@ public void Dispose() } } - public class UnitOfWorkCompleteHandle : IUnitOfWorkCompleteHandle + public class UnitOfWorkCompleteHandle : UnitOfWorkCompleteHandle, IUnitOfWorkCompleteHandle { - private readonly IUnitOfWork _uow; - public UnitOfWorkCompleteHandle(IUnitOfWork uow) + public UnitOfWorkCompleteHandle(UnitOfWork unitOfWork) : base(unitOfWork) { - _uow = uow; - } - private bool disposed = false; - protected virtual void Dispose(bool disposing) - { - if (!this.disposed) - { - if (disposing) - { - if (_uow.Context.IsTransactionStarted) - { - try - { - _uow.Rollback(); - } - catch - { - //do nothing - } - } - } - } - this.disposed = true; - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); } } } diff --git a/src/NuClear.Dapper/Utility/BatchFuncUtility.cs b/src/NuClear.Dapper/Utility/BatchFuncUtility.cs index 778513b..8db84f6 100644 --- a/src/NuClear.Dapper/Utility/BatchFuncUtility.cs +++ b/src/NuClear.Dapper/Utility/BatchFuncUtility.cs @@ -5,7 +5,7 @@ namespace NuClear.Dapper.Utility { /// - /// 根据数组 分页处理业务 工具类(一般用作dapper 根据in查询,dapper in 查询将数组 拼接为 参数,最多支持2000) + /// 根据数组 分页处理业务 工具类(一般用作dapper 根据in查询,dapper in 查询将数组 拼接为 参数,SqlServer最多支持2000) /// public static class BatchFuncUtility { @@ -23,13 +23,21 @@ public static List BatchFunc(string[] batchSource, Func !string.IsNullOrWhiteSpace(s)).ToArray(); if (filterNullBatchSource == null || !filterNullBatchSource.Any()) + { return new List(0); + } IEnumerable result = null; for (int i = 0; i < (filterNullBatchSource.Length - 1) / batchCount + 1; i++) { - if (result == null) result = func(filterNullBatchSource.Skip(i * batchCount).Take(batchCount).ToArray()); - else result = result.Union(func(filterNullBatchSource.Skip(i * batchCount).Take(batchCount).ToArray())); + if (result == null) + { + result = func(filterNullBatchSource.Skip(i * batchCount).Take(batchCount).ToArray()); + } + else + { + result = result.Union(func(filterNullBatchSource.Skip(i * batchCount).Take(batchCount).ToArray())); + } } return result.ToList(); @@ -45,17 +53,24 @@ public static List BatchFunc(string[] batchSource, Func public static List BatchFuncGenericSource(TSrouce[] batchSource, Func> func, int batchCount = 200) { - var filterNullBatchSource = batchSource?.ToArray(); if (filterNullBatchSource == null || !filterNullBatchSource.Any()) + { return new List(0); + } IEnumerable result = null; for (int i = 0; i < (filterNullBatchSource.Length - 1) / batchCount + 1; i++) { - if (result == null) result = func(filterNullBatchSource.Skip(i * batchCount).Take(batchCount).ToArray()); - else result = result.Union(func(filterNullBatchSource.Skip(i * batchCount).Take(batchCount).ToArray())); + if (result == null) + { + result = func(filterNullBatchSource.Skip(i * batchCount).Take(batchCount).ToArray()); + } + else + { + result = result.Union(func(filterNullBatchSource.Skip(i * batchCount).Take(batchCount).ToArray())); + } } return result.ToList(); @@ -75,7 +90,9 @@ public static void BatchAction(T[] batchSource, Action action, int batch var filterNullBatchSource = batchSource?.Where(s => s != null).ToArray(); if (filterNullBatchSource == null || !filterNullBatchSource.Any()) + { return; + } for (int i = 0; i < (filterNullBatchSource.Length - 1) / batchCount + 1; i++) {