From 9a057c34e2f8b3f2f02a79333d272c770a29c4a6 Mon Sep 17 00:00:00 2001 From: wwping Date: Thu, 23 Apr 2020 14:54:58 +0800 Subject: [PATCH 1/4] fix --- .../Core/Interfaces/IResolveExpression.cs | 696 +++++++++--------- .../Expressions/WhereExpression.cs | 160 ++-- .../Extension/ReflectExtension.cs | 4 +- Kogel.Dapper.Extension/Model/EntityObject.cs | 8 + Kogel.Dapper.Extension/SqlProvider.cs | 335 ++++----- 5 files changed, 613 insertions(+), 590 deletions(-) diff --git a/Kogel.Dapper.Extension/Core/Interfaces/IResolveExpression.cs b/Kogel.Dapper.Extension/Core/Interfaces/IResolveExpression.cs index 58f4f48..29d6d00 100644 --- a/Kogel.Dapper.Extension/Core/Interfaces/IResolveExpression.cs +++ b/Kogel.Dapper.Extension/Core/Interfaces/IResolveExpression.cs @@ -14,367 +14,375 @@ namespace Kogel.Dapper.Extension.Core.Interfaces { - public abstract class IResolveExpression - { - protected SqlProvider provider; - protected IProviderOption providerOption; - protected AbstractSet abstractSet => provider.Context.Set; + public abstract class IResolveExpression + { + protected SqlProvider provider; + protected IProviderOption providerOption; + protected AbstractSet abstractSet => provider.Context.Set; - public IResolveExpression(SqlProvider provider) - { - this.provider = provider; - this.providerOption = provider.ProviderOption; - } + public IResolveExpression(SqlProvider provider) + { + this.provider = provider; + this.providerOption = provider.ProviderOption; + } - /// - /// 字段列列表 - /// - private static Hashtable _tableFieldMap = new Hashtable(); + /// + /// 字段列列表 + /// + private static Hashtable _tableFieldMap = new Hashtable(); - /// - /// 根据反射对象获取表字段 - /// - /// - /// - public virtual string GetTableField(EntityObject entityObject) - { - lock (_tableFieldMap) - { - string fieldBuild = (string)_tableFieldMap[entityObject]; - if (fieldBuild == null) - { - var propertyInfos = entityObject.Properties; - string asName = entityObject.Name == entityObject.AsName ? providerOption.CombineFieldName(entityObject.AsName) : entityObject.AsName; - fieldBuild = string.Join(",", entityObject.FieldPairs.Select(field => $"{asName}.{providerOption.CombineFieldName(field.Value) }")); - _tableFieldMap.Add(entityObject, fieldBuild); - } - return fieldBuild; - } - } + /// + /// 根据反射对象获取表字段 + /// + /// + /// + public virtual string GetTableField(EntityObject entityObject) + { + lock (_tableFieldMap) + { + string fieldBuild = (string)_tableFieldMap[entityObject]; + if (fieldBuild == null) + { + var propertyInfos = entityObject.Properties; + string asName = entityObject.Name == entityObject.AsName ? providerOption.CombineFieldName(entityObject.AsName) : entityObject.AsName; + fieldBuild = string.Join(",", entityObject.FieldPairs.Select(field => $"{asName}.{providerOption.CombineFieldName(field.Value) }")); + _tableFieldMap.Add(entityObject, fieldBuild); + } + return fieldBuild; + } + } - /// - /// 解析查询字段 - /// - /// - /// - public abstract string ResolveSelect(int? topNum); + /// + /// 解析查询字段 + /// + /// + /// + public abstract string ResolveSelect(int? topNum); - /// - /// 解析查询条件 - /// - /// - /// - public virtual string ResolveWhereList(string prefix = null) - { - //添加Linq生成的sql条件和参数 - List lambdaExpressionList = abstractSet.WhereExpressionList; - StringBuilder builder = new StringBuilder("WHERE 1=1 "); - for (int i = 0; i < lambdaExpressionList.Count; i++) - { - var whereParam = new WhereExpression(lambdaExpressionList[i], $"{prefix}_{i}", provider); - builder.Append(whereParam.SqlCmd); - //参数 - foreach (var paramKey in whereParam.Param.ParameterNames) - { - abstractSet.Params.Add(paramKey, whereParam.Param.Get(paramKey)); - } - } - //添加自定义sql生成的条件和参数 - if (abstractSet.WhereBuilder != null && abstractSet.WhereBuilder.Length != 0) - { - //添加自定义条件sql - builder.Append(abstractSet.WhereBuilder); - } - return builder.ToString(); - } + /// + /// 解析查询条件 + /// + /// + /// + public virtual string ResolveWhereList(string prefix = null) + { + //添加Linq生成的sql条件和参数 + List lambdaExpressionList = abstractSet.WhereExpressionList; + StringBuilder builder = new StringBuilder("WHERE 1=1 "); + for (int i = 0; i < lambdaExpressionList.Count; i++) + { + var whereParam = new WhereExpression(lambdaExpressionList[i], $"{prefix}_{i}", provider); + builder.Append(whereParam.SqlCmd); + //参数 + foreach (var paramKey in whereParam.Param.ParameterNames) + { + abstractSet.Params.Add(paramKey, whereParam.Param.Get(paramKey)); + } + } + //添加自定义sql生成的条件和参数 + if (abstractSet.WhereBuilder != null && abstractSet.WhereBuilder.Length != 0) + { + //添加自定义条件sql + builder.Append(abstractSet.WhereBuilder); + } + return builder.ToString(); + } - /// - /// 解析分组 - /// - /// - public virtual string ResolveGroupBy() - { - StringBuilder builder = new StringBuilder(); - var groupExpression = abstractSet.GroupExpressionList; - if (groupExpression != null && groupExpression.Any()) - { - for (int i = 0; i < groupExpression.Count; i++) - { - var groupParam = new GroupExpression(groupExpression[i], $"Group_{i}", provider); - if (builder.Length != 0) - builder.Append(","); - builder.Append(groupParam.SqlCmd); - } - builder.Insert(0, " GROUP BY "); - } - return builder.ToString(); - } + /// + /// 解析分组 + /// + /// + public virtual string ResolveGroupBy() + { + StringBuilder builder = new StringBuilder(); + var groupExpression = abstractSet.GroupExpressionList; + if (groupExpression != null && groupExpression.Any()) + { + for (int i = 0; i < groupExpression.Count; i++) + { + var groupParam = new GroupExpression(groupExpression[i], $"Group_{i}", provider); + if (builder.Length != 0) + builder.Append(","); + builder.Append(groupParam.SqlCmd); + } + builder.Insert(0, " GROUP BY "); + } + return builder.ToString(); + } - /// - /// 解析分组聚合条件 - /// - /// - public virtual string ResolveHaving() - { - StringBuilder builder = new StringBuilder(); - var havingExpression = abstractSet.HavingExpressionList; - if (havingExpression != null && havingExpression.Any()) - { - for (int i = 0; i < havingExpression.Count; i++) - { - var whereParam = new WhereExpression(havingExpression[i], $"Having_{i}", provider); - builder.Append(whereParam.SqlCmd); - //参数 - foreach (var paramKey in whereParam.Param.ParameterNames) - { - abstractSet.Params.Add(paramKey, whereParam.Param.Get(paramKey)); - } - } - builder.Insert(0, " Having 1=1 "); - } - return builder.ToString(); - } + /// + /// 解析分组聚合条件 + /// + /// + public virtual string ResolveHaving() + { + StringBuilder builder = new StringBuilder(); + var havingExpression = abstractSet.HavingExpressionList; + if (havingExpression != null && havingExpression.Any()) + { + for (int i = 0; i < havingExpression.Count; i++) + { + var whereParam = new WhereExpression(havingExpression[i], $"Having_{i}", provider); + builder.Append(whereParam.SqlCmd); + //参数 + foreach (var paramKey in whereParam.Param.ParameterNames) + { + abstractSet.Params.Add(paramKey, whereParam.Param.Get(paramKey)); + } + } + builder.Insert(0, " Having 1=1 "); + } + return builder.ToString(); + } - /// - /// 解析排序 - /// - /// - public virtual string ResolveOrderBy() - { - var orderByList = abstractSet?.OrderbyExpressionList.Select(a => - { - var entity = EntityCache.QueryEntity(a.Key.Type.GenericTypeArguments[0]); - var columnName = a.Key.Body.GetCorrectPropertyName(); - return $"{entity.GetAsName(providerOption)}" + providerOption.CombineFieldName(columnName) + (a.Value == EOrderBy.Asc ? " ASC " : " DESC "); - }) ?? new List(); - if (!orderByList.Any() && (abstractSet.OrderbyBuilder == null || abstractSet.OrderbyBuilder.Length == 0)) - return ""; + /// + /// 解析排序 + /// + /// + public virtual string ResolveOrderBy() + { + var orderByList = abstractSet?.OrderbyExpressionList.Select(a => + { + var entity = EntityCache.QueryEntity(a.Key.Type.GenericTypeArguments[0]); + var columnName = a.Key.Body.GetCorrectPropertyName(); + return $"{entity.GetAsName(providerOption)}" + providerOption.CombineFieldName(columnName) + (a.Value == EOrderBy.Asc ? " ASC " : " DESC "); + }) ?? new List(); + if (!orderByList.Any() && (abstractSet.OrderbyBuilder == null || abstractSet.OrderbyBuilder.Length == 0)) + return ""; - return $"ORDER BY {string.Join(",", orderByList)} {abstractSet.OrderbyBuilder}"; - } + return $"ORDER BY {string.Join(",", orderByList)} {abstractSet.OrderbyBuilder}"; + } - /// - /// 解析查询总和 - /// - /// - /// - public abstract string ResolveSum(LambdaExpression selector); + /// + /// 解析查询总和 + /// + /// + /// + public abstract string ResolveSum(LambdaExpression selector); - /// - /// 解析查询最小值 - /// - /// - /// - public abstract string ResolveMax(LambdaExpression selector); + /// + /// 解析查询最小值 + /// + /// + /// + public abstract string ResolveMax(LambdaExpression selector); - /// - /// 解析查询最大值 - /// - /// - /// - public abstract string ResolveMin(LambdaExpression selector); + /// + /// 解析查询最大值 + /// + /// + /// + public abstract string ResolveMin(LambdaExpression selector); - /// - /// 解析查询更新 - /// - /// - /// - /// - public virtual string ResolveSelectOfUpdate(EntityObject entityObject, LambdaExpression selector) - { - var selectSql = ""; - if (selector == null) - { - var propertyBuilder = new StringBuilder(); - foreach (var propertyInfo in entityObject.Properties) - { - if (propertyBuilder.Length > 0) - propertyBuilder.Append(","); - propertyBuilder.AppendFormat($"INSERTED.{ providerOption.CombineFieldName(propertyInfo.GetColumnAttributeName())} { providerOption.CombineFieldName(propertyInfo.Name)}"); - } - selectSql = propertyBuilder.ToString(); - } - else - { - var nodeType = selector.Body.NodeType; - if (nodeType == ExpressionType.MemberAccess) - { - var columnName = ((MemberExpression)selector.Body).Member.GetColumnAttributeName(); - selectSql = "INSERTED." + providerOption.CombineFieldName(columnName); - } - else if (nodeType == ExpressionType.MemberInit) - { - var memberInitExpression = (MemberInitExpression)selector.Body; - selectSql = string.Join(",", memberInitExpression.Bindings.Select(a => "INSERTED." + providerOption.CombineFieldName(a.Member.GetColumnAttributeName()))); - } - } - return "OUTPUT " + selectSql; - } - /// - /// 解析更新 - /// - /// - /// - /// - public virtual UpdateExpression ResolveUpdate(Expression> updateExpression) - { - return new UpdateExpression(updateExpression, provider); - } + /// + /// 解析查询更新 + /// + /// + /// + /// + public virtual string ResolveSelectOfUpdate(EntityObject entityObject, LambdaExpression selector) + { + var selectSql = ""; + if (selector == null) + { + var propertyBuilder = new StringBuilder(); + foreach (var propertyInfo in entityObject.Properties) + { + if (propertyBuilder.Length > 0) + propertyBuilder.Append(","); + propertyBuilder.AppendFormat($"INSERTED.{ providerOption.CombineFieldName(propertyInfo.GetColumnAttributeName())} { providerOption.CombineFieldName(propertyInfo.Name)}"); + } + selectSql = propertyBuilder.ToString(); + } + else + { + var nodeType = selector.Body.NodeType; + if (nodeType == ExpressionType.MemberAccess) + { + var columnName = ((MemberExpression)selector.Body).Member.GetColumnAttributeName(); + selectSql = "INSERTED." + providerOption.CombineFieldName(columnName); + } + else if (nodeType == ExpressionType.MemberInit) + { + var memberInitExpression = (MemberInitExpression)selector.Body; + selectSql = string.Join(",", memberInitExpression.Bindings.Select(a => "INSERTED." + providerOption.CombineFieldName(a.Member.GetColumnAttributeName()))); + } + } + return "OUTPUT " + selectSql; + } + /// + /// 解析更新 + /// + /// + /// + /// + public virtual UpdateExpression ResolveUpdate(Expression> updateExpression) + { + return new UpdateExpression(updateExpression, provider); + } - /// - /// 解析更新语句 - /// - /// - /// - /// - /// - /// - public virtual string ResolveUpdates(T t, DynamicParameters Param, string[] excludeFields) - { - var entity = EntityCache.QueryEntity(t.GetType()); - var properties = entity.Properties; - StringBuilder builder = new StringBuilder(); - foreach (var propertiy in properties) - { - //是否是排除字段 - if (excludeFields != null && excludeFields.Contains(propertiy.Name)) - { - continue; - } - var customAttributes = propertiy.GetCustomAttributess(true); - //导航属性排除 - if (customAttributes.Any(x => x.GetType().Equals(typeof(ForeignKey)))) - { - continue; - } - //主键标识 - var typeAttribute = customAttributes.FirstOrDefault(x => x.GetType().Equals(typeof(Identity))); - if (typeAttribute != null) - { - var identity = typeAttribute as Identity; - //是否自增 - if (identity.IsIncrease) - { - continue; - } - } - object value = propertiy.GetValue(t); - string name = entity.FieldPairs[propertiy.Name]; - if (builder.Length != 0) - { - builder.Append(","); - } - builder.Append($"{providerOption.CombineFieldName(name)}={providerOption.ParameterPrefix}Update_{name}"); - Param.Add($"{providerOption.ParameterPrefix}Update_{name}", value); - } - builder.Insert(0, " SET "); - return builder.ToString(); - } - public virtual string ResolveWithNoLock(bool nolock) - { - return nolock ? "(NOLOCK)" : ""; - } + /// + /// 解析更新语句 + /// + /// + /// + /// + /// + /// + public virtual string ResolveUpdates(T t, DynamicParameters Param, string[] excludeFields) + { + var entity = EntityCache.QueryEntity(t.GetType()); + var properties = entity.Properties; + StringBuilder builder = new StringBuilder(); + foreach (var propertiy in properties) + { + //是否是排除字段 + if (excludeFields != null && excludeFields.Contains(propertiy.Name)) + { + continue; + } + var customAttributes = propertiy.GetCustomAttributess(true); + //导航属性排除 + if (customAttributes.Any(x => x.GetType().Equals(typeof(ForeignKey)))) + { + continue; + } + //主键标识 + var typeAttribute = customAttributes.FirstOrDefault(x => x.GetType().Equals(typeof(Identity))); + if (typeAttribute != null) + { + var identity = typeAttribute as Identity; + //是否自增 + if (identity.IsIncrease) + { + continue; + } + } - /// - /// 解析连表查询 - /// - /// - /// - /// - public virtual string ResolveJoinSql(List joinAssTables, ref string sql) - { - StringBuilder builder = new StringBuilder(Environment.NewLine); - if (joinAssTables.Count != 0) - { - sql = sql.TrimEnd(); - //循环拼接连表对象 - for (int i = 0; i < joinAssTables.Count; i++) - { - //当前连表对象 - var item = joinAssTables[i]; - if (item.IsMapperField == false) - { - continue; - } - item.MapperList.Clear(); - //连表实体 - var leftEntity = EntityCache.QueryEntity(item.TableType); - //默认连表 - if (item.Action == JoinAction.Default || item.Action == JoinAction.Navigation) - { - string leftTable = providerOption.CombineFieldName(item.LeftTabName); - builder.Append($@" {item.JoinMode.ToString()} JOIN + //主键标识 + var typeAttribute2 = customAttributes.FirstOrDefault(x => x.GetType().Equals(typeof(System.ComponentModel.DataAnnotations.KeyAttribute))); + if (typeAttribute2 != null) + { + continue; + + } + object value = propertiy.GetValue(t); + string name = entity.FieldPairs[propertiy.Name]; + if (builder.Length != 0) + { + builder.Append(","); + } + builder.Append($"{providerOption.CombineFieldName(name)}={providerOption.ParameterPrefix}Update_{name}"); + Param.Add($"{providerOption.ParameterPrefix}Update_{name}", value); + } + builder.Insert(0, " SET "); + return builder.ToString(); + } + public virtual string ResolveWithNoLock(bool nolock) + { + return nolock ? "(NOLOCK)" : ""; + } + + /// + /// 解析连表查询 + /// + /// + /// + /// + public virtual string ResolveJoinSql(List joinAssTables, ref string sql) + { + StringBuilder builder = new StringBuilder(Environment.NewLine); + if (joinAssTables.Count != 0) + { + sql = sql.TrimEnd(); + //循环拼接连表对象 + for (int i = 0; i < joinAssTables.Count; i++) + { + //当前连表对象 + var item = joinAssTables[i]; + if (item.IsMapperField == false) + { + continue; + } + item.MapperList.Clear(); + //连表实体 + var leftEntity = EntityCache.QueryEntity(item.TableType); + //默认连表 + if (item.Action == JoinAction.Default || item.Action == JoinAction.Navigation) + { + string leftTable = providerOption.CombineFieldName(item.LeftTabName); + builder.Append($@" {item.JoinMode.ToString()} JOIN {leftTable} {leftEntity.AsName} ON {leftEntity.AsName} .{providerOption.CombineFieldName(item.LeftAssName)} = {providerOption.CombineFieldName(item.RightTabName)} .{providerOption.CombineFieldName(item.RightAssName)} " + Environment.NewLine); - } - else//sql连表 - { - builder.Append(" " + item.JoinSql); - //判断是否需要显示连表的字段 - if (!item.IsMapperField) - { - continue; - } - } - //自定义返回 - if (provider.Context.Set.SelectExpression != null) - { - continue; - } - FieldDetailWith(ref sql, item, leftEntity); - } - } - return builder.ToString(); - } + } + else//sql连表 + { + builder.Append(" " + item.JoinSql); + //判断是否需要显示连表的字段 + if (!item.IsMapperField) + { + continue; + } + } + //自定义返回 + if (provider.Context.Set.SelectExpression != null) + { + continue; + } + FieldDetailWith(ref sql, item, leftEntity); + } + } + return builder.ToString(); + } - /// - /// 字段处理 - /// - /// - /// - /// - /// - private string FieldDetailWith(ref string masterSql, JoinAssTable joinAssTable, EntityObject joinEntity) - { - StringBuilder sqlBuilder = new StringBuilder(); - //表名称 - string joinTableName = joinEntity.AsName == joinEntity.Name ? providerOption.CombineFieldName(joinEntity.Name) : joinEntity.AsName; - //查询的字段 - var fieldPairs = joinAssTable.SelectFieldPairs != null && joinAssTable.SelectFieldPairs.Any() ? joinAssTable.SelectFieldPairs : joinEntity.FieldPairs; - foreach (string fieldValue in fieldPairs.Values) - { - if (masterSql.LastIndexOf(',') == masterSql.Length - 1 && sqlBuilder.Length == 0) - sqlBuilder.Append($"{joinTableName}."); - else - //首先添加表名称 - sqlBuilder.Append($",{joinTableName}."); - //字段 - string field = providerOption.CombineFieldName(fieldValue); - //字符出现的次数 - int repeatCount = masterSql.Split(new string[] { field }, StringSplitOptions.None).Length - 1; - //添加字段 - sqlBuilder.Append(field); - if (repeatCount > 0) - { - sqlBuilder.Append($" AS {fieldValue}_{repeatCount}"); - joinAssTable.MapperList.Add(fieldValue, $"{fieldValue}_{repeatCount}"); - } - else - { - joinAssTable.MapperList.Add(fieldValue, fieldValue); - } - } - //导航属性目前有点问题 - //var joinEntityType = joinAssTable.IsDto == false ? joinEntity.Type : joinAssTable.DtoType; - ////重新注册实体映射 - //SqlMapper.SetTypeMap(joinEntityType, new CustomPropertyTypeMap(joinEntityType, - // (type, column) => - // type.GetPropertys(joinAssTable.MapperList.FirstOrDefault(x => x.Value.Equals(column)).Key) - // ), true); - //设置sql字段 - masterSql += sqlBuilder; - return masterSql; - } - } + /// + /// 字段处理 + /// + /// + /// + /// + /// + private string FieldDetailWith(ref string masterSql, JoinAssTable joinAssTable, EntityObject joinEntity) + { + StringBuilder sqlBuilder = new StringBuilder(); + //表名称 + string joinTableName = joinEntity.AsName == joinEntity.Name ? providerOption.CombineFieldName(joinEntity.Name) : joinEntity.AsName; + //查询的字段 + var fieldPairs = joinAssTable.SelectFieldPairs != null && joinAssTable.SelectFieldPairs.Any() ? joinAssTable.SelectFieldPairs : joinEntity.FieldPairs; + foreach (string fieldValue in fieldPairs.Values) + { + if (masterSql.LastIndexOf(',') == masterSql.Length - 1 && sqlBuilder.Length == 0) + sqlBuilder.Append($"{joinTableName}."); + else + //首先添加表名称 + sqlBuilder.Append($",{joinTableName}."); + //字段 + string field = providerOption.CombineFieldName(fieldValue); + //字符出现的次数 + int repeatCount = masterSql.Split(new string[] { field }, StringSplitOptions.None).Length - 1; + //添加字段 + sqlBuilder.Append(field); + if (repeatCount > 0) + { + sqlBuilder.Append($" AS {fieldValue}_{repeatCount}"); + joinAssTable.MapperList.Add(fieldValue, $"{fieldValue}_{repeatCount}"); + } + else + { + joinAssTable.MapperList.Add(fieldValue, fieldValue); + } + } + //导航属性目前有点问题 + //var joinEntityType = joinAssTable.IsDto == false ? joinEntity.Type : joinAssTable.DtoType; + ////重新注册实体映射 + //SqlMapper.SetTypeMap(joinEntityType, new CustomPropertyTypeMap(joinEntityType, + // (type, column) => + // type.GetPropertys(joinAssTable.MapperList.FirstOrDefault(x => x.Value.Equals(column)).Key) + // ), true); + //设置sql字段 + masterSql += sqlBuilder; + return masterSql; + } + } } diff --git a/Kogel.Dapper.Extension/Expressions/WhereExpression.cs b/Kogel.Dapper.Extension/Expressions/WhereExpression.cs index 9dabbe3..fa41ed5 100644 --- a/Kogel.Dapper.Extension/Expressions/WhereExpression.cs +++ b/Kogel.Dapper.Extension/Expressions/WhereExpression.cs @@ -5,86 +5,86 @@ namespace Kogel.Dapper.Extension.Expressions { - /// - /// 解析查询条件 - /// - public sealed class WhereExpression : WhereExpressionVisitor - { - #region sql指令 - private readonly StringBuilder _sqlCmd; - /// - /// sql指令 - /// - public string SqlCmd { get; } - /// - /// 参数 - /// - public new DynamicParameters Param { get; } - #endregion - /// - /// 解析条件对象 - /// - /// 表达式 - /// 参数标记 - /// - public WhereExpression(LambdaExpression expression, string prefix, SqlProvider provider) : base(provider) - { - this._sqlCmd = new StringBuilder(100); - this.Param = new DynamicParameters(); - this.providerOption = provider.ProviderOption; - //开始解析对象 - Visit(expression); - //开始拼接成条件 - this._sqlCmd.Append(base.SpliceField); - this.SqlCmd = " AND " + this._sqlCmd.ToString(); - if (string.IsNullOrEmpty(prefix)) - { - this.Param.AddDynamicParams(base.Param); - } - else - { - //加上参数标记 - foreach (var paramName in base.Param.ParameterNames) - { - string newName = paramName + prefix; - object value = base.Param.Get(paramName); - this.SqlCmd = this.SqlCmd.Replace(paramName, newName); - this.Param.Add(newName, value); - } - } - } + /// + /// 解析查询条件 + /// + public sealed class WhereExpression : WhereExpressionVisitor + { + #region sql指令 + private readonly StringBuilder _sqlCmd; + /// + /// sql指令 + /// + public string SqlCmd { get; } + /// + /// 参数 + /// + public new DynamicParameters Param { get; } + #endregion + /// + /// 解析条件对象 + /// + /// 表达式 + /// 参数标记 + /// + public WhereExpression(LambdaExpression expression, string prefix, SqlProvider provider) : base(provider) + { + this._sqlCmd = new StringBuilder(100); + this.Param = new DynamicParameters(); + this.providerOption = provider.ProviderOption; + //开始解析对象 + Visit(expression); + //开始拼接成条件 + this._sqlCmd.Append(base.SpliceField); + this.SqlCmd = " AND " + this._sqlCmd.ToString(); + if (string.IsNullOrEmpty(prefix)) + { + this.Param.AddDynamicParams(base.Param); + } + else + { + //加上参数标记 + foreach (var paramName in base.Param.ParameterNames) + { + string newName = (paramName + prefix).Replace("_", "__"); + object value = base.Param.Get(paramName); + this.SqlCmd = this.SqlCmd.Replace(paramName, newName); + this.Param.Add(newName, value); + } + } + } - /// - /// 解析二元表达式 - /// - /// - /// - protected override Expression VisitBinary(BinaryExpression node) - { - var binaryWhere = new BinaryExpressionVisitor(node, base.Provider); - this._sqlCmd.Append(binaryWhere.SpliceField); - base.Param.AddDynamicParams(binaryWhere.Param); - return node; - } + /// + /// 解析二元表达式 + /// + /// + /// + protected override Expression VisitBinary(BinaryExpression node) + { + var binaryWhere = new BinaryExpressionVisitor(node, base.Provider); + this._sqlCmd.Append(binaryWhere.SpliceField); + base.Param.AddDynamicParams(binaryWhere.Param); + return node; + } - /// - /// 解析!不等于(!里只能包含一个条件) - /// - /// - /// - protected override Expression VisitUnary(UnaryExpression node) - { - if (node.NodeType == ExpressionType.Not) - { - this._sqlCmd.Append(" Not ("); - Visit(node.Operand); - this._sqlCmd.Append(") "); - } - else - { - Visit(node.Operand); - } - return node; - } - } + /// + /// 解析!不等于(!里只能包含一个条件) + /// + /// + /// + protected override Expression VisitUnary(UnaryExpression node) + { + if (node.NodeType == ExpressionType.Not) + { + this._sqlCmd.Append(" Not ("); + Visit(node.Operand); + this._sqlCmd.Append(") "); + } + else + { + Visit(node.Operand); + } + return node; + } + } } diff --git a/Kogel.Dapper.Extension/Extension/ReflectExtension.cs b/Kogel.Dapper.Extension/Extension/ReflectExtension.cs index 14a8278..bcafe2f 100644 --- a/Kogel.Dapper.Extension/Extension/ReflectExtension.cs +++ b/Kogel.Dapper.Extension/Extension/ReflectExtension.cs @@ -10,7 +10,7 @@ public static class ReflectExtension { public static PropertyInfo GetKeyPropertity(this object obj) { - var properties = EntityCache.QueryEntity(obj.GetType()).Properties.Where(a => a.GetCustomAttribute() != null).ToArray(); + var properties = EntityCache.QueryEntity(obj.GetType()).Properties.Where(a => a.GetCustomAttribute() != null || a.GetCustomAttribute() != null).ToArray(); if (!properties.Any()) throw new DapperExtensionException($"the {nameof(obj)} entity with no KeyAttribute Propertity"); @@ -22,7 +22,7 @@ public static PropertyInfo GetKeyPropertity(this object obj) } public static PropertyInfo GetKeyPropertity(this Type typeInfo) { - var properties = EntityCache.QueryEntity(typeInfo).Properties.Where(a => a.GetCustomAttribute() != null).ToArray(); + var properties = EntityCache.QueryEntity(typeInfo).Properties.Where(a => a.GetCustomAttribute() != null || a.GetCustomAttribute() != null).ToArray(); if (!properties.Any()) throw new DapperExtensionException($"the type {nameof(typeInfo.FullName)} entity with no KeyAttribute Propertity"); diff --git a/Kogel.Dapper.Extension/Model/EntityObject.cs b/Kogel.Dapper.Extension/Model/EntityObject.cs index a3a0078..f7fdbfa 100644 --- a/Kogel.Dapper.Extension/Model/EntityObject.cs +++ b/Kogel.Dapper.Extension/Model/EntityObject.cs @@ -142,6 +142,14 @@ public EntityObject(Type type) EntityFieldList[EntityFieldList.Count - 1].IsIdentity = true; EntityFieldList[EntityFieldList.Count - 1].IsIncrease = (identityAttribute as Identity).IsIncrease; } + + var identityAttribute2 = item.GetCustomAttributes(true).FirstOrDefault(x => x.GetType().Equals(typeof(System.ComponentModel.DataAnnotations.KeyAttribute))); + if (identityAttribute2 != null) + { + this.Identitys = this.FieldPairs[item.Name]; + EntityFieldList[EntityFieldList.Count - 1].IsIdentity = true; + EntityFieldList[EntityFieldList.Count - 1].IsIncrease = true; + } } } this.Properties = PropertyInfoList.ToArray(); diff --git a/Kogel.Dapper.Extension/SqlProvider.cs b/Kogel.Dapper.Extension/SqlProvider.cs index a3549d7..1763110 100644 --- a/Kogel.Dapper.Extension/SqlProvider.cs +++ b/Kogel.Dapper.Extension/SqlProvider.cs @@ -13,168 +13,175 @@ namespace Kogel.Dapper.Extension { - public abstract class SqlProvider - { - public AbstractDataBaseContext Context { get; set; } - - protected SqlProvider() - { - Params = new DynamicParameters(); - JoinList = new List(); - AsTableNameDic = new Dictionary(); - } - - public abstract IProviderOption ProviderOption { get; set; } - - public string SqlString { get; set; } - /// - /// 连接对象集合 - /// - public List JoinList { get; set; } - /// - /// 参数对象 - /// - public DynamicParameters Params { get; set; } - /// - /// 重命名目录 - /// - public Dictionary AsTableNameDic { get; set; } - - public abstract SqlProvider FormatGet(); - - public abstract SqlProvider FormatToList(); - - public abstract SqlProvider FormatToPageList(int pageIndex, int pageSize); - - public abstract SqlProvider FormatCount(); - - public abstract SqlProvider FormatDelete(); - - public abstract SqlProvider FormatInsert(T entity, string[] excludeFields); - - public abstract SqlProvider FormatInsertIdentity(T entity, string[] excludeFields); - - public abstract SqlProvider FormatUpdate(Expression> updateExpression); - - public abstract SqlProvider FormatUpdate(T entity, string[] excludeFields, bool isBatch = false); - - public abstract SqlProvider FormatSum(LambdaExpression sumExpression); - - public abstract SqlProvider FormatMin(LambdaExpression MinExpression); - - public abstract SqlProvider FormatMax(LambdaExpression MaxExpression); - - public abstract SqlProvider FormatUpdateSelect(Expression> updator); - - public abstract SqlProvider CreateNew(); - - /// - /// 获取表名称 - /// - /// - /// - /// 连接查询时会用到 - /// - - public string FormatTableName(bool isNeedFrom = true, bool isAsName = true, Type tableType = null) - { - var entity = EntityCache.QueryEntity(tableType == null ? Context.Set.TableType : tableType); - string schema = string.IsNullOrEmpty(entity.Schema) ? "" : ProviderOption.CombineFieldName(entity.Schema) + "."; - string fromName = entity.Name; - //函数AsTableName优先级大于一切 - string asTableName; - if (AsTableNameDic.TryGetValue(entity.Type, out asTableName)) - { - fromName = asTableName; - } - //是否存在实体特性中的AsName标记 - if (isAsName) - fromName = entity.AsName.Equals(fromName) ? ProviderOption.CombineFieldName(fromName) : $"{ProviderOption.CombineFieldName(fromName)} {entity.AsName}"; - SqlString = $" {schema}{fromName} "; - if (isNeedFrom) - SqlString = " FROM " + SqlString; - - return SqlString; - } - - protected string[] FormatInsertParamsAndValues(T t, string[] excludeFields = null) - { - var paramSqlBuilder = new StringBuilder(64); - var valueSqlBuilder = new StringBuilder(64); - - var entity = EntityCache.QueryEntity(t.GetType()); - var properties = entity.Properties; - - var isAppend = false; - foreach (var propertiy in properties) - { - //是否是排除字段 - if (excludeFields != null && excludeFields.Contains(propertiy.Name)) - { - continue; - } - var customAttributes = propertiy.GetCustomAttributess(true); - //导航属性排除 - if (customAttributes.Any(x => x.GetType().Equals(typeof(ForeignKey)))) - { - continue; - } - //主键标识 - var typeAttribute = customAttributes.FirstOrDefault(x => x.GetType().Equals(typeof(Identity))); - if (typeAttribute != null) - { - var identity = typeAttribute as Identity; - //是否自增 - if (identity.IsIncrease) - { - continue; - } - } - //排除掉时间格式为最小值的字段 - if (propertiy.PropertyType == typeof(DateTime)) - { - if (Convert.ToDateTime(propertiy.GetValue(t)) == DateTime.MinValue) - { - continue; - } - } - if (isAppend) - { - paramSqlBuilder.Append(","); - valueSqlBuilder.Append(","); - } - var name = propertiy.GetColumnAttributeName(); - paramSqlBuilder.AppendFormat("{0}{1}{2}", ProviderOption.OpenQuote, entity.FieldPairs[name], ProviderOption.CloseQuote); - valueSqlBuilder.Append(ProviderOption.ParameterPrefix + name); - Params.Add(ProviderOption.ParameterPrefix + name, propertiy.GetValue(t)); - isAppend = true; - } - return new[] { paramSqlBuilder.ToString(), valueSqlBuilder.ToString() }; - } - - protected DataBaseContext DataBaseContext() - { - return (DataBaseContext)Context; - } - - /// - /// 根据主键获取条件 - /// - /// - /// - /// - protected string GetIdentityWhere(T entity, DynamicParameters param) - { - var entityObject = EntityCache.QueryEntity(typeof(T)); - if (string.IsNullOrEmpty(entityObject.Identitys)) - throw new DapperExtensionException("主键不存在!请前往实体类使用[Identity]特性设置主键。"); - //获取主键数据 - var id = entityObject.Properties - .FirstOrDefault(x => x.Name == entityObject.Identitys) - .GetValue(entity); - //设置参数 - param.Add(entityObject.Identitys, id); - return $" AND {entityObject.Identitys}={ProviderOption.ParameterPrefix}{entityObject.Identitys} "; - } - } + public abstract class SqlProvider + { + public AbstractDataBaseContext Context { get; set; } + + protected SqlProvider() + { + Params = new DynamicParameters(); + JoinList = new List(); + AsTableNameDic = new Dictionary(); + } + + public abstract IProviderOption ProviderOption { get; set; } + + public string SqlString { get; set; } + /// + /// 连接对象集合 + /// + public List JoinList { get; set; } + /// + /// 参数对象 + /// + public DynamicParameters Params { get; set; } + /// + /// 重命名目录 + /// + public Dictionary AsTableNameDic { get; set; } + + public abstract SqlProvider FormatGet(); + + public abstract SqlProvider FormatToList(); + + public abstract SqlProvider FormatToPageList(int pageIndex, int pageSize); + + public abstract SqlProvider FormatCount(); + + public abstract SqlProvider FormatDelete(); + + public abstract SqlProvider FormatInsert(T entity, string[] excludeFields); + + public abstract SqlProvider FormatInsertIdentity(T entity, string[] excludeFields); + + public abstract SqlProvider FormatUpdate(Expression> updateExpression); + + public abstract SqlProvider FormatUpdate(T entity, string[] excludeFields, bool isBatch = false); + + public abstract SqlProvider FormatSum(LambdaExpression sumExpression); + + public abstract SqlProvider FormatMin(LambdaExpression MinExpression); + + public abstract SqlProvider FormatMax(LambdaExpression MaxExpression); + + public abstract SqlProvider FormatUpdateSelect(Expression> updator); + + public abstract SqlProvider CreateNew(); + + /// + /// 获取表名称 + /// + /// + /// + /// 连接查询时会用到 + /// + + public string FormatTableName(bool isNeedFrom = true, bool isAsName = true, Type tableType = null) + { + var entity = EntityCache.QueryEntity(tableType == null ? Context.Set.TableType : tableType); + string schema = string.IsNullOrEmpty(entity.Schema) ? "" : ProviderOption.CombineFieldName(entity.Schema) + "."; + string fromName = entity.Name; + //函数AsTableName优先级大于一切 + string asTableName; + if (AsTableNameDic.TryGetValue(entity.Type, out asTableName)) + { + fromName = asTableName; + } + //是否存在实体特性中的AsName标记 + if (isAsName) + fromName = entity.AsName.Equals(fromName) ? ProviderOption.CombineFieldName(fromName) : $"{ProviderOption.CombineFieldName(fromName)} {entity.AsName}"; + SqlString = $" {schema}{fromName} "; + if (isNeedFrom) + SqlString = " FROM " + SqlString; + + return SqlString; + } + + protected string[] FormatInsertParamsAndValues(T t, string[] excludeFields = null) + { + var paramSqlBuilder = new StringBuilder(64); + var valueSqlBuilder = new StringBuilder(64); + + var entity = EntityCache.QueryEntity(t.GetType()); + var properties = entity.Properties; + + var isAppend = false; + foreach (var propertiy in properties) + { + //是否是排除字段 + if (excludeFields != null && excludeFields.Contains(propertiy.Name)) + { + continue; + } + var customAttributes = propertiy.GetCustomAttributess(true); + //导航属性排除 + if (customAttributes.Any(x => x.GetType().Equals(typeof(ForeignKey)))) + { + continue; + } + //主键标识 + var typeAttribute = customAttributes.FirstOrDefault(x => x.GetType().Equals(typeof(Identity))); + if (typeAttribute != null) + { + var identity = typeAttribute as Identity; + //是否自增 + if (identity.IsIncrease) + { + continue; + } + } + + var typeAttribute2 = customAttributes.FirstOrDefault(x => x.GetType().Equals(typeof(System.ComponentModel.DataAnnotations.KeyAttribute))); + if (typeAttribute2 != null) + { + continue; + + } + //排除掉时间格式为最小值的字段 + if (propertiy.PropertyType == typeof(DateTime)) + { + if (Convert.ToDateTime(propertiy.GetValue(t)) == DateTime.MinValue) + { + continue; + } + } + if (isAppend) + { + paramSqlBuilder.Append(","); + valueSqlBuilder.Append(","); + } + var name = propertiy.GetColumnAttributeName(); + paramSqlBuilder.AppendFormat("{0}{1}{2}", ProviderOption.OpenQuote, entity.FieldPairs[name], ProviderOption.CloseQuote); + valueSqlBuilder.Append(ProviderOption.ParameterPrefix + name); + Params.Add(ProviderOption.ParameterPrefix + name, propertiy.GetValue(t)); + isAppend = true; + } + return new[] { paramSqlBuilder.ToString(), valueSqlBuilder.ToString() }; + } + + protected DataBaseContext DataBaseContext() + { + return (DataBaseContext)Context; + } + + /// + /// 根据主键获取条件 + /// + /// + /// + /// + protected string GetIdentityWhere(T entity, DynamicParameters param) + { + var entityObject = EntityCache.QueryEntity(typeof(T)); + if (string.IsNullOrEmpty(entityObject.Identitys)) + throw new DapperExtensionException("主键不存在!请前往实体类使用[Identity]特性设置主键。"); + //获取主键数据 + var id = entityObject.Properties + .FirstOrDefault(x => x.Name == entityObject.Identitys) + .GetValue(entity); + //设置参数 + param.Add(entityObject.Identitys, id); + return $" AND {entityObject.Identitys}={ProviderOption.ParameterPrefix}{entityObject.Identitys} "; + } + } } From 6fd59714b942bf92874590f192e36a8f300ceb8f Mon Sep 17 00:00:00 2001 From: wwping Date: Thu, 23 Apr 2020 14:57:41 +0800 Subject: [PATCH 2/4] fix --- .../Core/Interfaces/IDapperSet.cs | 102 +++++++++--------- .../Kogel.Dapper.Extension.csproj | 1 + 2 files changed, 52 insertions(+), 51 deletions(-) diff --git a/Kogel.Dapper.Extension/Core/Interfaces/IDapperSet.cs b/Kogel.Dapper.Extension/Core/Interfaces/IDapperSet.cs index d311ecb..d0ac346 100644 --- a/Kogel.Dapper.Extension/Core/Interfaces/IDapperSet.cs +++ b/Kogel.Dapper.Extension/Core/Interfaces/IDapperSet.cs @@ -7,66 +7,66 @@ namespace Kogel.Dapper.Extension { - public abstract class AbstractSet - { - /// - /// 数据解析提供方 - /// - public SqlProvider SqlProvider; + public abstract class AbstractSet + { + /// + /// 数据解析提供方 + /// + public SqlProvider SqlProvider; - /// - /// 表类型 - /// - public Type TableType { get; set; } + /// + /// 表类型 + /// + public Type TableType { get; set; } - /// - /// [已弃用]只用来生成对象 - /// - internal LambdaExpression WhereExpression { get; set; } + /// + /// [已弃用]只用来生成对象 + /// + internal LambdaExpression WhereExpression { get; set; } - /// - /// 条件表达式对象 - /// - internal List WhereExpressionList { get; set; } + /// + /// 条件表达式对象 + /// + public List WhereExpressionList { get; set; } - /// - /// 表达式排序集合 - /// - internal Dictionary OrderbyExpressionList { get; set; } + /// + /// 表达式排序集合 + /// + public Dictionary OrderbyExpressionList { get; set; } - /// - /// 字符串排序 - /// - internal StringBuilder OrderbyBuilder { get; set; } + /// + /// 字符串排序 + /// + internal StringBuilder OrderbyBuilder { get; set; } - /// - /// 字段查询对象 - /// - public LambdaExpression SelectExpression { get; set; } + /// + /// 字段查询对象 + /// + public LambdaExpression SelectExpression { get; set; } - /// - /// 是否锁表(with(nolock)) - /// - public bool NoLock { get; set; } + /// + /// 是否锁表(with(nolock)) + /// + public bool NoLock { get; set; } - /// - /// sql字符串对象 - /// - internal StringBuilder WhereBuilder { get; set; } + /// + /// sql字符串对象 + /// + internal StringBuilder WhereBuilder { get; set; } - /// - /// sql参数对象 - /// - internal DynamicParameters Params { get => SqlProvider.Params; set => SqlProvider.Params.AddDynamicParams(value); } + /// + /// sql参数对象 + /// + internal DynamicParameters Params { get => SqlProvider.Params; set => SqlProvider.Params.AddDynamicParams(value); } - /// - /// 分组表达式对象 - /// - internal List GroupExpressionList { get; set; } + /// + /// 分组表达式对象 + /// + internal List GroupExpressionList { get; set; } - /// - /// 分组聚合条件 - /// - internal List HavingExpressionList { get; set; } - } + /// + /// 分组聚合条件 + /// + internal List HavingExpressionList { get; set; } + } } diff --git a/Kogel.Dapper.Extension/Kogel.Dapper.Extension.csproj b/Kogel.Dapper.Extension/Kogel.Dapper.Extension.csproj index 8ed153d..55004cf 100644 --- a/Kogel.Dapper.Extension/Kogel.Dapper.Extension.csproj +++ b/Kogel.Dapper.Extension/Kogel.Dapper.Extension.csproj @@ -32,6 +32,7 @@ https://www.cnblogs.com/kogel/p/10805696.html + From 0f7f297adff43ead4861f5f52d9d2b740d15ad2e Mon Sep 17 00:00:00 2001 From: wwping Date: Fri, 3 Jul 2020 17:44:06 +0800 Subject: [PATCH 3/4] fix --- Kogel.Dapper.Extension/Core/SetQ/QuerySet.cs | 11 +++++++++-- Kogel.Dapper.Extension/Expressions/WhereExpression.cs | 9 +++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/Kogel.Dapper.Extension/Core/SetQ/QuerySet.cs b/Kogel.Dapper.Extension/Core/SetQ/QuerySet.cs index 46ef98b..cb0436f 100644 --- a/Kogel.Dapper.Extension/Core/SetQ/QuerySet.cs +++ b/Kogel.Dapper.Extension/Core/SetQ/QuerySet.cs @@ -81,12 +81,19 @@ public QuerySet FieldMatch() #region 条件 public QuerySet Where(Expression> predicate) { - WhereExpressionList.Add(predicate); + if (predicate != null) + { + WhereExpressionList.Add(predicate); + } + return this; } public QuerySet Where(Expression> predicate) { - WhereExpressionList.Add(predicate); + if(predicate != null) + { + WhereExpressionList.Add(predicate); + } return this; } diff --git a/Kogel.Dapper.Extension/Expressions/WhereExpression.cs b/Kogel.Dapper.Extension/Expressions/WhereExpression.cs index fa41ed5..77cc19b 100644 --- a/Kogel.Dapper.Extension/Expressions/WhereExpression.cs +++ b/Kogel.Dapper.Extension/Expressions/WhereExpression.cs @@ -36,7 +36,12 @@ public WhereExpression(LambdaExpression expression, string prefix, SqlProvider p Visit(expression); //开始拼接成条件 this._sqlCmd.Append(base.SpliceField); - this.SqlCmd = " AND " + this._sqlCmd.ToString(); + string sql = this._sqlCmd.ToString(); + if (!string.IsNullOrWhiteSpace(sql)) + { + this.SqlCmd = " AND " + sql; + } + if (string.IsNullOrEmpty(prefix)) { this.Param.AddDynamicParams(base.Param); @@ -46,7 +51,7 @@ public WhereExpression(LambdaExpression expression, string prefix, SqlProvider p //加上参数标记 foreach (var paramName in base.Param.ParameterNames) { - string newName = (paramName + prefix).Replace("_", "__"); + string newName = (paramName + prefix).Replace("_", "xx"); object value = base.Param.Get(paramName); this.SqlCmd = this.SqlCmd.Replace(paramName, newName); this.Param.Add(newName, value); From 69522710c2f359e1ac17ae9c0f4dca6fe6eec6a1 Mon Sep 17 00:00:00 2001 From: wwping Date: Mon, 6 Jul 2020 10:17:02 +0800 Subject: [PATCH 4/4] fix1 --- Kogel.Dapper.Extension/Core/Interfaces/IDapperSet.cs | 4 ++-- .../Core/Interfaces/IResolveExpression.cs | 7 +++++++ Kogel.Dapper.Extension/Extension/ReflectExtension.cs | 3 ++- Kogel.Dapper.Extension/Kogel.Dapper.Extension.csproj | 1 + Kogel.Dapper.Extension/Model/EntityObject.cs | 9 +++++++++ Kogel.Dapper.Extension/SqlProvider.cs | 7 +++++++ "Kogel.Dapper.Extension/\344\277\256\346\224\271.txt" | 2 ++ 7 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 "Kogel.Dapper.Extension/\344\277\256\346\224\271.txt" diff --git a/Kogel.Dapper.Extension/Core/Interfaces/IDapperSet.cs b/Kogel.Dapper.Extension/Core/Interfaces/IDapperSet.cs index 6c0b099..6f8311d 100644 --- a/Kogel.Dapper.Extension/Core/Interfaces/IDapperSet.cs +++ b/Kogel.Dapper.Extension/Core/Interfaces/IDapperSet.cs @@ -27,12 +27,12 @@ public abstract class AbstractSet /// /// 条件表达式对象 /// - internal List WhereExpressionList { get; set; } + public List WhereExpressionList { get; set; } /// /// 表达式排序集合 /// - internal Dictionary OrderbyExpressionList { get; set; } + public Dictionary OrderbyExpressionList { get; set; } /// /// 字符串排序 diff --git a/Kogel.Dapper.Extension/Core/Interfaces/IResolveExpression.cs b/Kogel.Dapper.Extension/Core/Interfaces/IResolveExpression.cs index fa8af6b..62a02e8 100644 --- a/Kogel.Dapper.Extension/Core/Interfaces/IResolveExpression.cs +++ b/Kogel.Dapper.Extension/Core/Interfaces/IResolveExpression.cs @@ -7,6 +7,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; using System.Linq; using System.Linq.Expressions; using System.Text; @@ -260,6 +261,12 @@ public virtual string ResolveUpdates(T t, DynamicParameters param, string[] e continue; } } + var typeAttribute2 = customAttributes.FirstOrDefault(x => x.GetType().Equals(typeof(KeyAttribute))); + if (typeAttribute2 != null) + { + continue; + + } object value = propertiy.GetValue(t); string name = entity.FieldPairs[propertiy.Name]; if (builder.Length != 0) diff --git a/Kogel.Dapper.Extension/Extension/ReflectExtension.cs b/Kogel.Dapper.Extension/Extension/ReflectExtension.cs index d9c2d4b..ea374b6 100644 --- a/Kogel.Dapper.Extension/Extension/ReflectExtension.cs +++ b/Kogel.Dapper.Extension/Extension/ReflectExtension.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Reflection; using Kogel.Dapper.Extension; +using System.ComponentModel.DataAnnotations; namespace Kogel.Dapper.Extension.Extension { @@ -10,7 +11,7 @@ public static class ReflectExtension { public static PropertyInfo GetKeyPropertity(this object obj) { - var properties = EntityCache.QueryEntity(obj.GetType()).Properties.Where(a => a.GetCustomAttribute() != null).ToArray(); + var properties = EntityCache.QueryEntity(obj.GetType()).Properties.Where(a => a.GetCustomAttribute() != null || a.GetCustomAttribute() != null).ToArray(); if (!properties.Any()) throw new DapperExtensionException($"the {nameof(obj)} entity with no KeyAttribute Propertity"); diff --git a/Kogel.Dapper.Extension/Kogel.Dapper.Extension.csproj b/Kogel.Dapper.Extension/Kogel.Dapper.Extension.csproj index a2531b7..1ea8936 100644 --- a/Kogel.Dapper.Extension/Kogel.Dapper.Extension.csproj +++ b/Kogel.Dapper.Extension/Kogel.Dapper.Extension.csproj @@ -35,6 +35,7 @@ https://www.cnblogs.com/kogel/p/10805696.html + diff --git a/Kogel.Dapper.Extension/Model/EntityObject.cs b/Kogel.Dapper.Extension/Model/EntityObject.cs index a3a0078..4d1a995 100644 --- a/Kogel.Dapper.Extension/Model/EntityObject.cs +++ b/Kogel.Dapper.Extension/Model/EntityObject.cs @@ -7,6 +7,7 @@ using Kogel.Dapper.Extension.Core.Interfaces; using System.Linq.Expressions; using System.Data; +using System.ComponentModel.DataAnnotations; namespace Kogel.Dapper.Extension.Model { @@ -142,6 +143,14 @@ public EntityObject(Type type) EntityFieldList[EntityFieldList.Count - 1].IsIdentity = true; EntityFieldList[EntityFieldList.Count - 1].IsIncrease = (identityAttribute as Identity).IsIncrease; } + + var identityAttribute2 = item.GetCustomAttributes(true).FirstOrDefault(x => x.GetType().Equals(typeof(KeyAttribute))); + if (identityAttribute2 != null) + { + this.Identitys = this.FieldPairs[item.Name]; + EntityFieldList[EntityFieldList.Count - 1].IsIdentity = true; + EntityFieldList[EntityFieldList.Count - 1].IsIncrease = true; + } } } this.Properties = PropertyInfoList.ToArray(); diff --git a/Kogel.Dapper.Extension/SqlProvider.cs b/Kogel.Dapper.Extension/SqlProvider.cs index c523146..c8a15f6 100644 --- a/Kogel.Dapper.Extension/SqlProvider.cs +++ b/Kogel.Dapper.Extension/SqlProvider.cs @@ -10,6 +10,7 @@ using Kogel.Dapper.Extension.Core.Interfaces; using Kogel.Dapper.Extension.Helper; using Kogel.Dapper.Extension; +using System.ComponentModel.DataAnnotations; namespace Kogel.Dapper.Extension { @@ -132,6 +133,12 @@ protected string[] FormatInsertParamsAndValues(T t, string[] excludeFields = continue; } } + var typeAttribute2 = customAttributes.FirstOrDefault(x => x.GetType().Equals(typeof(KeyAttribute))); + if (typeAttribute2 != null) + { + continue; + + } //排除掉时间格式为最小值的字段 if (propertiy.PropertyType == typeof(DateTime)) { diff --git "a/Kogel.Dapper.Extension/\344\277\256\346\224\271.txt" "b/Kogel.Dapper.Extension/\344\277\256\346\224\271.txt" new file mode 100644 index 0000000..dbec9b0 --- /dev/null +++ "b/Kogel.Dapper.Extension/\344\277\256\346\224\271.txt" @@ -0,0 +1,2 @@ +在 Identity 加 KeyAttribute +在where 加 null判断 \ No newline at end of file