Update Core

This commit is contained in:
sunkaixuan
2018-10-14 16:21:29 +08:00
parent 46c08c11dd
commit a98508f3f6
22 changed files with 484 additions and 30 deletions

View File

@@ -195,7 +195,7 @@ namespace SqlSugar
{
oldTableName = this.SqlBuilder.GetTranslationTableName(oldTableName);
newTableName = this.SqlBuilder.GetTranslationTableName(newTableName);
string sql = string.Format(this.BackupTableSql, newTableName, oldTableName, maxBackupDataRows);
string sql = string.Format(this.BackupTableSql, maxBackupDataRows, newTableName, oldTableName);
this.Context.Ado.ExecuteCommand(sql);
return true;
}

View File

@@ -158,6 +158,7 @@ namespace SqlSugar
column.DecimalDigits = sugarColumn.DecimalDigits;
column.OracleSequenceName = sugarColumn.OracleSequenceName;
column.IsOnlyIgnoreInsert = sugarColumn.IsOnlyIgnoreInsert;
column.IsEnableUpdateVersionValidation = sugarColumn.IsEnableUpdateVersionValidation;
}
else
{

View File

@@ -289,7 +289,7 @@ namespace SqlSugar
Value = column.Value,
DbColumnName = column.Key,
PropertyName = column.Key,
PropertyType = UtilMethods.GetUnderType(column.Value.GetType()),
PropertyType = column.Value == null? DBNull.Value.GetType(): UtilMethods.GetUnderType(column.Value.GetType()),
TableId = i
};
if (columnInfo.PropertyType.IsEnum())

View File

@@ -22,6 +22,8 @@ namespace SqlSugar
public ISqlBuilder SqlBuilder { get; set; }
public MappingTableList OldMappingTableList { get; set; }
public MappingTableList QueryableMappingTableList { get; set; }
public Action<T> MapperAction { get; set; }
public Action<T, MapperCache<T>> MapperActionWithCache { get; set; }
public bool IsCache { get; set; }
public int CacheTime { get; set; }
public bool IsAs { get; set; }
@@ -70,6 +72,16 @@ namespace SqlSugar
return this;
}
public virtual ISugarQueryable<T> Mapper(Action<T> mapperAction) {
this.MapperAction = mapperAction;
return this;
}
public virtual ISugarQueryable<T> Mapper(Action<T, MapperCache<T>> mapperAction)
{
this.MapperActionWithCache = mapperAction;
return this;
}
public virtual ISugarQueryable<T> AddParameters(object parameters)
{
if (parameters != null)
@@ -179,6 +191,14 @@ namespace SqlSugar
Where(SqlBuilder.SqlFalse);
return this;
}
if (pkValues.Length == 1&& pkValues.First() is IEnumerable) {
var newValues =new List<object>();
foreach (var item in pkValues.First() as IEnumerable)
{
newValues.Add(item);
}
return In(newValues);
}
var pks = GetPrimaryKeys().Select(it => SqlBuilder.GetTranslationTableName(it)).ToList();
Check.Exception(pks == null || pks.Count != 1, "Queryable.In(params object[] pkValues): Only one primary key");
string filed = pks.FirstOrDefault();
@@ -427,6 +447,21 @@ namespace SqlSugar
{
return _Select<TResult>(expression);
}
public virtual ISugarQueryable<TResult> Select<TResult>()
{
var isJoin = this.QueryBuilder.JoinExpression!=null;
if (isJoin)
{
var selectValue = new SugarMapper(this.Context).GetSelectValue<TResult>(this.QueryBuilder);
return this.Select<TResult>(selectValue);
}
else
{
return this.Select<TResult>(this.SqlBuilder.SqlSelectAll);
}
}
public virtual ISugarQueryable<TResult> Select<TResult>(string selectValue)
{
var result = InstanceFactory.GetQueryable<TResult>(this.Context.CurrentConnectionConfig);
@@ -988,7 +1023,7 @@ namespace SqlSugar
{
var isSingle = QueryBuilder.IsSingle();
var lamResult = QueryBuilder.GetExpressionValue(expression, isSingle ? ResolveExpressType.FieldSingle : ResolveExpressType.FieldMultiple);
var result= Min<TResult>(lamResult.GetResultString());
var result = Min<TResult>(lamResult.GetResultString());
QueryBuilder.SelectValue = null;
return result;
}
@@ -1002,7 +1037,7 @@ namespace SqlSugar
{
var isSingle = QueryBuilder.IsSingle();
var lamResult = QueryBuilder.GetExpressionValue(expression, isSingle ? ResolveExpressType.FieldSingle : ResolveExpressType.FieldMultiple);
var reslut= Max<TResult>(lamResult.GetResultString());
var reslut = Max<TResult>(lamResult.GetResultString());
QueryBuilder.SelectValue = null;
return reslut;
}
@@ -1010,7 +1045,7 @@ namespace SqlSugar
{
var isSingle = QueryBuilder.IsSingle();
var lamResult = QueryBuilder.GetExpressionValue(expression, isSingle ? ResolveExpressType.FieldSingle : ResolveExpressType.FieldMultiple);
var reslut= Sum<TResult>(lamResult.GetResultString());
var reslut = Sum<TResult>(lamResult.GetResultString());
QueryBuilder.SelectValue = null;
return reslut;
}
@@ -1081,8 +1116,42 @@ namespace SqlSugar
result = GetData<TResult>(sqlObj);
}
RestoreMapping();
_Mapper(result);
return result;
}
protected void _Mapper<TResult>(List<TResult> result)
{
if (this.MapperAction != null)
{
foreach (TResult item in result)
{
if (typeof(TResult) == typeof(T))
{
this.MapperAction((T)Convert.ChangeType(item, typeof(T)));
}
else {
Check.Exception(true, "{0} and {1} are not a type, Try .select().mapper().ToList", typeof(TResult).FullName,typeof(T).FullName);
}
}
}
if (this.MapperActionWithCache != null)
{
if (typeof(TResult) == typeof(T))
{
var list = (List<T>)Convert.ChangeType(result, typeof(List<T>));
var mapperCache = new MapperCache<T>(list,this.Context);
foreach (T item in list)
{
this.MapperActionWithCache(item, mapperCache);
}
}
else {
Check.Exception(true, "{0} and {1} are not a type, Try .select().mapper().ToList", typeof(TResult).FullName, typeof(T).FullName);
}
}
}
protected int GetCount()
{
var sql = string.Empty;
@@ -1184,7 +1253,7 @@ namespace SqlSugar
{
if (result.HasValue())
{
if (UtilMethods.GetRootBaseType(entityType).HasValue() &&UtilMethods.GetRootBaseType(entityType) == UtilConstants.ModelType)
if (UtilMethods.GetRootBaseType(entityType).HasValue() && UtilMethods.GetRootBaseType(entityType) == UtilConstants.ModelType)
{
foreach (var item in result)
{
@@ -1218,6 +1287,7 @@ namespace SqlSugar
asyncQueryableBuilder.OrderByValue = this.QueryBuilder.OrderByValue;
asyncQueryableBuilder.IsDisabledGobalFilter = this.QueryBuilder.IsDisabledGobalFilter;
asyncQueryableBuilder.PartitionByValue = this.QueryBuilder.PartitionByValue;
asyncQueryableBuilder.JoinExpression = this.QueryBuilder.JoinExpression;
return asyncQueryable;
}
#endregion

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
@@ -41,6 +42,8 @@ namespace SqlSugar
public object SelectValue { get; set; }
public string SelectCacheKey { get; set; }
public string EntityName { get; set; }
public Type EntityType { get; set; }
public string TableWithString { get; set; }
public string GroupByValue { get; set; }
@@ -49,6 +52,7 @@ namespace SqlSugar
public int JoinIndex { get; set; }
public bool IsDisabledGobalFilter { get; set; }
public virtual List<SugarParameter> Parameters { get; set; }
public Expression JoinExpression { get; set; }
public Dictionary<string, string> EasyJoinInfos
{
get
@@ -328,6 +332,17 @@ namespace SqlSugar
return string.Format(temp, sql.ToString(), (pageIndex - 1) * pageSize+1, pageIndex * pageSize);
}
public virtual string GetSelectByItems(List<KeyValuePair<string, object>> items)
{
var array = items.Select(it => {
dynamic dynamicObj = this.Context.Utilities.DeserializeObject<dynamic>(this.Context.Utilities.SerializeObject(it.Value));
var dbName =Builder.GetTranslationColumnName( (string)(dynamicObj.dbName));
var asName = Builder.GetTranslationColumnName((string)(dynamicObj.asName));
return string.Format("{0}.{1} AS {2}",it.Key,dbName,asName);
});
return string.Join(",",array);
}
public virtual string ToJoinString(JoinQueryInfo joinInfo)
{
return string.Format(
@@ -485,6 +500,7 @@ namespace SqlSugar
return this.GroupByValue;
}
}
#endregion
private string GetTableName(string entityName)

View File

@@ -23,6 +23,7 @@ namespace SqlSugar
private List<string> IgnoreColumnNameList { get; set; }
private List<string> WhereColumnList { get; set; }
private bool IsOffIdentity { get; set; }
private bool IsVersionValidation { get; set; }
public MappingTableList OldMappingTableList { get; set; }
public bool IsAs { get; set; }
public virtual int ExecuteCommand()
@@ -31,9 +32,11 @@ namespace SqlSugar
AutoRemoveDataCache();
Check.Exception(UpdateBuilder.WhereValues.IsNullOrEmpty() && GetPrimaryKeys().IsNullOrEmpty(), "You cannot have no primary key and no conditions");
string sql = UpdateBuilder.ToSqlString();
ValidateVersion();
RestoreMapping();
return this.Ado.ExecuteCommand(sql, UpdateBuilder.Parameters == null ? null : UpdateBuilder.Parameters.ToArray());
}
public bool ExecuteCommandHasChange()
{
return this.ExecuteCommand() > 0;
@@ -64,7 +67,8 @@ namespace SqlSugar
IsAs = true;
OldMappingTableList = this.Context.MappingTables;
this.Context.MappingTables = this.Context.Utilities.TranslateCopy(this.Context.MappingTables);
if (this.Context.MappingTables.Any(it => it.EntityName == entityName)) {
if (this.Context.MappingTables.Any(it => it.EntityName == entityName))
{
this.Context.MappingTables.Add(this.Context.MappingTables.First(it => it.EntityName == entityName).DbTableName, tableName);
}
this.Context.MappingTables.Add(entityName, tableName);
@@ -76,6 +80,12 @@ namespace SqlSugar
return this;
}
public IUpdateable<T> IsEnableUpdateVersionValidation()
{
this.IsVersionValidation = true;
return this;
}
public IUpdateable<T> IgnoreColumns(bool ignoreAllNullColumns, bool isOffIdentity = false)
{
UpdateBuilder.IsOffIdentity = isOffIdentity;
@@ -110,7 +120,7 @@ namespace SqlSugar
{
var moreSetts = this.Context.CurrentConnectionConfig.MoreSettings;
var extService = this.Context.CurrentConnectionConfig.ConfigureExternalServices;
if (moreSetts != null && moreSetts.IsAutoRemoveDataCache && extService!=null&& extService.DataInfoCacheService!=null)
if (moreSetts != null && moreSetts.IsAutoRemoveDataCache && extService != null && extService.DataInfoCacheService != null)
{
this.RemoveDataCache();
}
@@ -150,12 +160,13 @@ namespace SqlSugar
return this;
}
public IUpdateable<T> UpdateColumns(Expression<Func<T, bool>> columns) {
public IUpdateable<T> UpdateColumns(Expression<Func<T, bool>> columns)
{
var binaryExp = columns.Body as BinaryExpression;
Check.Exception(!binaryExp.NodeType.IsIn(ExpressionType.Equal), "No support {0}", columns.ToString());
Check.Exception(!(binaryExp.Left is MemberExpression)&& !(binaryExp.Left is UnaryExpression), "No support {0}", columns.ToString());
Check.Exception(!(binaryExp.Left is MemberExpression) && !(binaryExp.Left is UnaryExpression), "No support {0}", columns.ToString());
Check.Exception(ExpressionTool.IsConstExpression(binaryExp.Left as MemberExpression), "No support {0}", columns.ToString());
var expResult = UpdateBuilder.GetExpressionValue(columns, ResolveExpressType.WhereSingle).GetResultString().Replace("))",") )").Replace("((", "( (").Trim().TrimStart('(').TrimEnd(')');
var expResult = UpdateBuilder.GetExpressionValue(columns, ResolveExpressType.WhereSingle).GetResultString().Replace("))", ") )").Replace("((", "( (").Trim().TrimStart('(').TrimEnd(')');
string key = SqlBuilder.GetNoTranslationColumnName(expResult);
UpdateBuilder.SetValues.Add(new KeyValuePair<string, string>(SqlBuilder.GetTranslationColumnName(key), expResult));
this.UpdateBuilder.DbColumnInfoList = this.UpdateBuilder.DbColumnInfoList.Where(it => UpdateBuilder.SetValues.Any(v => SqlBuilder.GetNoTranslationColumnName(v.Key).Equals(it.DbColumnName, StringComparison.CurrentCultureIgnoreCase) || SqlBuilder.GetNoTranslationColumnName(v.Key).Equals(it.PropertyName, StringComparison.CurrentCultureIgnoreCase)) || it.IsPrimarykey == true).ToList();
@@ -189,7 +200,7 @@ namespace SqlSugar
UpdateBuilder.SetValues.Add(new KeyValuePair<string, string>(SqlBuilder.GetTranslationColumnName(key), item));
}
}
this.UpdateBuilder.DbColumnInfoList = this.UpdateBuilder.DbColumnInfoList.Where(it => UpdateBuilder.SetValues.Any(v => SqlBuilder.GetNoTranslationColumnName(v.Key).Equals(it.DbColumnName,StringComparison.CurrentCultureIgnoreCase)|| SqlBuilder.GetNoTranslationColumnName(v.Key).Equals(it.PropertyName,StringComparison.CurrentCultureIgnoreCase)) || it.IsPrimarykey == true).ToList();
this.UpdateBuilder.DbColumnInfoList = this.UpdateBuilder.DbColumnInfoList.Where(it => UpdateBuilder.SetValues.Any(v => SqlBuilder.GetNoTranslationColumnName(v.Key).Equals(it.DbColumnName, StringComparison.CurrentCultureIgnoreCase) || SqlBuilder.GetNoTranslationColumnName(v.Key).Equals(it.PropertyName, StringComparison.CurrentCultureIgnoreCase)) || it.IsPrimarykey == true).ToList();
return this;
}
[Obsolete("Use IUpdateable<T> IgnoreColumns(bool ignoreAllNullColumns, bool isOffIdentity = false);")]
@@ -211,20 +222,22 @@ namespace SqlSugar
public IUpdateable<T> Where(string whereSql, object parameters = null)
{
if (whereSql.HasValue()) {
if (whereSql.HasValue())
{
UpdateBuilder.WhereValues.Add(whereSql);
}
if (parameters != null) {
if (parameters != null)
{
UpdateBuilder.Parameters.AddRange(Context.Ado.GetParameters(parameters));
}
return this;
}
public IUpdateable<T> Where(string fieldName,string conditionalType, object fieldValue)
public IUpdateable<T> Where(string fieldName, string conditionalType, object fieldValue)
{
var whereSql=this.SqlBuilder.GetWhere(fieldName, conditionalType,0);
var whereSql = this.SqlBuilder.GetWhere(fieldName, conditionalType, 0);
this.Where(whereSql);
string parameterName = this.SqlBuilder.SqlParameterKeyWord + fieldName+ "0";
string parameterName = this.SqlBuilder.SqlParameterKeyWord + fieldName + "0";
this.UpdateBuilder.Parameters.Add(new SugarParameter(parameterName, fieldValue));
return this;
}
@@ -259,7 +272,7 @@ namespace SqlSugar
foreach (var item in UpdateObjs)
{
List<DbColumnInfo> updateItem = new List<DbColumnInfo>();
var isDic = item is Dictionary<string,object>;
var isDic = item is Dictionary<string, object>;
if (isDic)
{
SetUpdateItemByDic(i, item, updateItem);
@@ -273,14 +286,14 @@ namespace SqlSugar
}
private void SetUpdateItemByDic(int i, T item, List<DbColumnInfo> updateItem)
{
foreach (var column in item as Dictionary<string,object>)
foreach (var column in item as Dictionary<string, object>)
{
var columnInfo = new DbColumnInfo()
{
Value = column.Value,
DbColumnName =column.Key,
DbColumnName = column.Key,
PropertyName = column.Key,
PropertyType = UtilMethods.GetUnderType(column.Value.GetType()),
PropertyType = column.Value == null ? DBNull.Value.GetType() : UtilMethods.GetUnderType(column.Value.GetType()),
TableId = i
};
if (columnInfo.PropertyType.IsEnum())
@@ -331,7 +344,8 @@ namespace SqlSugar
foreach (var item in this.UpdateBuilder.DbColumnInfoList)
{
if (this.UpdateBuilder.Parameters == null) this.UpdateBuilder.Parameters = new List<SugarParameter>();
if (this.UpdateBuilder.SetValues.Any(it =>this.SqlBuilder.GetNoTranslationColumnName(it.Key) == item.PropertyName)) {
if (this.UpdateBuilder.SetValues.Any(it => this.SqlBuilder.GetNoTranslationColumnName(it.Key) == item.PropertyName))
{
continue;
}
this.UpdateBuilder.Parameters.Add(new SugarParameter(this.SqlBuilder.SqlParameterKeyWord + item.DbColumnName, item.Value, item.PropertyType));
@@ -449,5 +463,53 @@ namespace SqlSugar
asyncUpdateableBuilder.SetValues = this.UpdateBuilder.SetValues;
return asyncUpdateable;
}
private void ValidateVersion()
{
var versionColumn = this.EntityInfo.Columns.FirstOrDefault(it => it.IsEnableUpdateVersionValidation);
var pks = this.UpdateBuilder.DbColumnInfoList.Where(it => it.IsPrimarykey).ToList();
if (versionColumn != null && this.IsVersionValidation)
{
Check.Exception(pks.IsNullOrEmpty(), "UpdateVersionValidation the primary key is required.");
List<IConditionalModel> conModels = new List<IConditionalModel>();
foreach (var item in pks)
{
conModels.Add(new ConditionalModel() { FieldName = item.DbColumnName, ConditionalType = ConditionalType.Equal, FieldValue = item.Value.ObjToString() });
}
var dbInfo = this.Context.Queryable<T>().Where(conModels).First();
if (dbInfo != null)
{
var currentVersion = this.EntityInfo.Type.GetProperty(versionColumn.PropertyName).GetValue(UpdateObjs.Last(), null);
var dbVersion = this.EntityInfo.Type.GetProperty(versionColumn.PropertyName).GetValue(dbInfo, null);
Check.Exception(currentVersion == null, "UpdateVersionValidation entity property {0} is not null", versionColumn.PropertyName);
Check.Exception(dbVersion == null, "UpdateVersionValidation database column {0} is not null", versionColumn.DbColumnName);
if (versionColumn.PropertyInfo.PropertyType.IsIn(UtilConstants.IntType, UtilConstants.LongType))
{
if (Convert.ToInt64(dbVersion) > Convert.ToInt64(currentVersion))
{
throw new VersionExceptions(string.Format("UpdateVersionValidation {0} Not the latest version ", versionColumn.PropertyName));
}
}
else if (versionColumn.PropertyInfo.PropertyType.IsIn(UtilConstants.DateType))
{
if (dbVersion.ObjToDate() > currentVersion.ObjToDate())
{
throw new VersionExceptions(string.Format("UpdateVersionValidation {0} Not the latest version ", versionColumn.PropertyName));
}
}
else if (versionColumn.PropertyInfo.PropertyType.IsIn(UtilConstants.ByteArrayType))
{
if (UtilMethods.GetLong((byte[])dbVersion)>UtilMethods.GetLong((byte[])currentVersion))
{
throw new VersionExceptions(string.Format("UpdateVersionValidation {0} Not the latest version ", versionColumn.PropertyName));
}
}
else
{
Check.ThrowNotSupportedException(string.Format("UpdateVersionValidation Not Supported Type [ {0} ] , {1}", versionColumn.PropertyInfo.PropertyType, versionColumn.PropertyName));
}
}
}
}
}
}

View File

@@ -19,6 +19,7 @@ namespace SqlSugar
public bool IsNullable { get; set; }
public bool IsIdentity { get; set; }
public bool IsPrimarykey { get; set; }
public bool IsEnableUpdateVersionValidation { get; set; }
public string EntityName { get; set; }
public string DbTableName { get; set; }
public bool IsIgnore { get; set; }

View File

@@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SqlSugar
{
public class MapperCache<T>
{
private Dictionary<string, object> caches = new Dictionary<string, object>();
private List<T> _list { get; set; }
private SqlSugarClient _context { get; set; }
private MapperCache()
{
}
public MapperCache(List<T> list, SqlSugarClient context)
{
_list = list;
_context = context;
}
public Result Get<Result>(Func<List<T>, Result> action)
{
string key = "Get" + typeof(Result) + action.GetHashCode().ToString();
if (caches.ContainsKey(key))
{
return (Result)caches[key];
}
else
{
var result = action(_list);
caches.Add(key, result);
return result;
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, double?> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, double?>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, double> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, double>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, decimal?> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, decimal?>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, decimal> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, decimal>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, int?> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result,int?>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, int> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, int>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, long?> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, long?>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, long> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, long>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, string> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, string>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, Guid> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, Guid>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, Guid?> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, Guid?>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, DateTime> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, DateTime>(action, key);
}
}
public List<Result> GetListByPrimaryKeys<Result>(Func<T, DateTime?> action) where Result : class, new()
{
{
string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
return GetListByPrimaryKeys<Result, DateTime?>(action, key);
}
}
private List<Result> GetListByPrimaryKeys<Result,FieldType>(Func<T, FieldType> action, string key) where Result : class, new()
{
if (caches.ContainsKey(key))
{
return (List<Result>)caches[key];
}
else
{
var ids = _list.Select(action).ToList().Distinct().ToList();
var result = _context.Queryable<Result>().In(ids).ToList();
caches.Add(key, result);
return result;
}
}
}
}

View File

@@ -105,6 +105,15 @@ namespace SqlSugar
get { return _IsOnlyIgnoreInsert; }
set { _IsOnlyIgnoreInsert = value; }
}
private bool _IsEnableUpdateVersionValidation;
public bool IsEnableUpdateVersionValidation {
get { return _IsEnableUpdateVersionValidation; }
set { _IsEnableUpdateVersionValidation = value; }
}
}
}

View File

@@ -100,7 +100,7 @@ namespace SqlSugar
public static TResult AggregateAvg<TResult>(TResult thisValue) { throw new NotSupportedException("Can only be used in expressions"); }
public static TResult AggregateMin<TResult>(TResult thisValue) { throw new NotSupportedException("Can only be used in expressions"); }
public static TResult AggregateMax<TResult>(TResult thisValue) { throw new NotSupportedException("Can only be used in expressions"); }
public static int AggregateCount(int thisValue) { throw new NotSupportedException("Can only be used in expressions"); }
public static int AggregateCount<TResult>(TResult thisValue) { throw new NotSupportedException("Can only be used in expressions"); }
public static TResult MappingColumn<TResult>(TResult oldColumnName,string newColumnName) { throw new NotSupportedException("Can only be used in expressions"); }
/// <summary>
///Example: new NewT(){name=SqlFunc.GetSelfAndAutoFill(it)} Generated SQL it.*

View File

@@ -256,6 +256,7 @@ namespace SqlSugar
newContext.MappingColumns = this.Context.MappingColumns;
newContext.MappingTables = this.Context.MappingTables;
newContext.IgnoreComumnList = this.Context.IgnoreComumnList;
newContext.IsSingle = this.Context.IsSingle;
newContext.SqlFuncServices = this.Context.SqlFuncServices;
newContext.Resolve(item, this.Context.IsJoin ? ResolveExpressType.WhereMultiple : ResolveExpressType.WhereSingle);
this.Context.Index = newContext.Index;
@@ -278,7 +279,7 @@ namespace SqlSugar
protected string GetNewExpressionValue(Expression item)
{
var newContext = this.Context.GetCopyContext();
var newContext = this.Context.GetCopyContextWithMapping();
newContext.Resolve(item, this.Context.IsJoin ? ResolveExpressType.WhereMultiple : ResolveExpressType.WhereSingle);
this.Context.Index = newContext.Index;
this.Context.ParameterIndex = newContext.ParameterIndex;

View File

@@ -43,7 +43,11 @@ namespace SqlSugar
public string GetValue(Expression expression = null)
{
var exp = expression as MethodCallExpression;
return "MAX("+SubTools.GetMethodValue(this.Context, exp.Arguments[0], ResolveExpressType.FieldSingle)+")";
var argExp = exp.Arguments[0];
var result = "MAX(" + SubTools.GetMethodValue(Context, argExp, ResolveExpressType.WhereMultiple) + ")";
var selfParameterName = Context.GetTranslationColumnName((argExp as LambdaExpression).Parameters.First().Name) + UtilConstants.Dot;
result = result.Replace(selfParameterName, string.Empty);
return result;
}
}
}

View File

@@ -43,7 +43,11 @@ namespace SqlSugar
public string GetValue(Expression expression = null)
{
var exp = expression as MethodCallExpression;
return "MIN(" + SubTools.GetMethodValue(this.Context, exp.Arguments[0], ResolveExpressType.FieldSingle) + ")";
var argExp = exp.Arguments[0];
var result = "MIN(" + SubTools.GetMethodValue(Context, argExp, ResolveExpressType.WhereMultiple) + ")";
var selfParameterName = Context.GetTranslationColumnName((argExp as LambdaExpression).Parameters.First().Name) + UtilConstants.Dot;
result = result.Replace(selfParameterName, string.Empty);
return result;
}
}
}

View File

@@ -6,7 +6,7 @@ using System.Text;
namespace SqlSugar
{
public class SubSum:ISubOperation
public class SubSum : ISubOperation
{
public bool HasWhere
{
@@ -43,7 +43,11 @@ namespace SqlSugar
public string GetValue(Expression expression = null)
{
var exp = expression as MethodCallExpression;
return "SUM("+SubTools.GetMethodValue(this.Context, exp.Arguments[0], ResolveExpressType.FieldSingle)+")";
var argExp = exp.Arguments[0];
var result = "SUM(" + SubTools.GetMethodValue(Context, argExp, ResolveExpressType.WhereMultiple)+")";
var selfParameterName = Context.GetTranslationColumnName((argExp as LambdaExpression).Parameters.First().Name) + UtilConstants.Dot;
result = result.Replace(selfParameterName, string.Empty);
return result;
}
}
}

View File

@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace SqlSugar
{
public class SugarMapper
{
private SqlSugarClient _context;
public SugarMapper(SqlSugarClient context)
{
_context = context;
}
public string GetSelectValue<TResult>(QueryBuilder queryBuilder)
{
string result = string.Empty;
var veiwModel = _context.EntityMaintenance.GetEntityInfo<TResult>();
var exp = (queryBuilder.JoinExpression as LambdaExpression);
List<KeyValuePair<string, object>> selectItems = new List<KeyValuePair<string, object>>();
foreach (var viewColumn in veiwModel.Columns)
{
var exParsmeters = exp.Parameters.Select(it => new { shortName = it.Name, type = it.Type }).ToList();
foreach (var expPars in exParsmeters)
{
var columns = _context.EntityMaintenance.GetEntityInfo(expPars.type).Columns.Where(it => it.IsIgnore == false);
var joinModelDbColumns = columns.Select(it =>
new { asName = it.PropertyName, dbName = _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type) }).ToList();
var joinModelProperties = columns.Select(it =>
new { asName = _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type), dbName = _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type) }).ToList();
var joinModelDbColumnsWithType = columns.Select(it =>
new { asName = (expPars.type.Name + it.PropertyName), dbName = _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type) }).ToList();
var joinModelPropertiesWithTye = columns.Select(it =>
new { asName = (expPars.type.Name + _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type)), dbName = _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type) }).ToList();
var joinModelDbColumns_WithType = columns.Select(it =>
new { asName = (expPars.type.Name +"_"+ it.PropertyName), dbName = _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type) }).ToList();
var joinModelProperties_WithType = columns.Select(it =>
new { asName = (expPars.type.Name +"_"+ _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type)), dbName = _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type) }).ToList();
var joinModelDbColumnsWithSN = columns.Select(it =>
new { asName = (expPars.shortName + it.PropertyName), dbName = _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type) }).ToList();
var joinModelPropertiesWithSN = columns.Select(it =>
new { asName = (expPars.shortName + _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type)), dbName = _context.EntityMaintenance.GetDbColumnName(it.PropertyName, expPars.type) }).ToList();
if (joinModelDbColumns.Any(it => it.asName.Equals(viewColumn.PropertyName,StringComparison.CurrentCultureIgnoreCase)))
{
var value = joinModelDbColumns.First(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase));
if (viewColumn.PropertyName.Equals(value.asName, StringComparison.CurrentCultureIgnoreCase))
selectItems.Add(new KeyValuePair<string, object>(expPars.shortName,value));
break;
}
if (joinModelProperties.Any(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase)))
{
var value = joinModelProperties.First(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase));
if (viewColumn.PropertyName.Equals(value.asName, StringComparison.CurrentCultureIgnoreCase))
selectItems.Add(new KeyValuePair<string, object>(expPars.shortName, value));
break;
}
if (joinModelDbColumnsWithType.Any(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase)))
{
var value = joinModelDbColumnsWithType.First(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase));
if (viewColumn.PropertyName.Equals(value.asName, StringComparison.CurrentCultureIgnoreCase))
selectItems.Add(new KeyValuePair<string, object>(expPars.shortName, value));
break;
}
if (joinModelPropertiesWithTye.Any(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase)))
{
var value = joinModelPropertiesWithTye.First(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase));
if (viewColumn.PropertyName.Equals(value.asName, StringComparison.CurrentCultureIgnoreCase))
selectItems.Add(new KeyValuePair<string, object>(expPars.shortName, value));
break;
}
if (joinModelDbColumns_WithType.Any(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase)))
{
var value = joinModelDbColumns_WithType.First(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase));
if (viewColumn.PropertyName.Equals(value.asName, StringComparison.CurrentCultureIgnoreCase))
selectItems.Add(new KeyValuePair<string, object>(expPars.shortName, value));
break;
}
if (joinModelProperties_WithType.Any(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase)))
{
var value = joinModelProperties_WithType.First(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase));
if (viewColumn.PropertyName.Equals(value.asName, StringComparison.CurrentCultureIgnoreCase))
selectItems.Add(new KeyValuePair<string, object>(expPars.shortName, value));
break;
}
if (joinModelDbColumnsWithSN.Any(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase)))
{
var value = joinModelDbColumnsWithSN.First(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase));
if (viewColumn.PropertyName.Equals(value.asName, StringComparison.CurrentCultureIgnoreCase))
selectItems.Add(new KeyValuePair<string, object>(expPars.shortName, value));
break;
}
if (joinModelPropertiesWithSN.Any(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase)))
{
var value = joinModelPropertiesWithSN.First(it => it.asName.Equals(viewColumn.PropertyName, StringComparison.CurrentCultureIgnoreCase));
if (viewColumn.PropertyName.Equals(value.asName, StringComparison.CurrentCultureIgnoreCase))
selectItems.Add(new KeyValuePair<string, object>(expPars.shortName, value));
break;
}
}
}
result = queryBuilder.GetSelectByItems(selectItems);
return result;
}
}
}

View File

@@ -315,6 +315,7 @@ namespace SqlSugar
List<SugarParameter> paramters = new List<SugarParameter>();
queryable.SqlBuilder.QueryBuilder.JoinQueryInfos = this.GetJoinInfos(queryable.SqlBuilder, joinExpression, ref paramters, ref shortName, types);
queryable.SqlBuilder.QueryBuilder.TableShortName = shortName;
queryable.SqlBuilder.QueryBuilder.JoinExpression = joinExpression;
if (paramters != null)
{
queryable.SqlBuilder.QueryBuilder.Parameters.AddRange(paramters);
@@ -326,6 +327,7 @@ namespace SqlSugar
string shortName = string.Empty;
queryable.SqlBuilder.QueryBuilder.EasyJoinInfos = this.GetEasyJoinInfo(joinExpression, ref shortName, queryable.SqlBuilder, types);
queryable.SqlBuilder.QueryBuilder.TableShortName = shortName;
queryable.SqlBuilder.QueryBuilder.JoinExpression=joinExpression;
}
#endregion

View File

@@ -19,6 +19,8 @@ namespace SqlSugar
ISugarQueryable<T> AS(string tableName);
ISugarQueryable<T> With(string withString);
ISugarQueryable<T> Filter(string FilterName, bool isDisabledGobalFilter = false);
ISugarQueryable<T> Mapper(Action<T> mapperAction);
ISugarQueryable<T> Mapper(Action<T, MapperCache<T>> mapperAction);
ISugarQueryable<T> AddParameters(object parameters);
ISugarQueryable<T> AddParameters(SugarParameter[] parameters);
ISugarQueryable<T> AddParameters(List<SugarParameter> parameters);
@@ -74,6 +76,7 @@ namespace SqlSugar
Task<bool> AnyAsync();
ISugarQueryable<TResult> Select<TResult>(Expression<Func<T, TResult>> expression);
ISugarQueryable<TResult> Select<TResult>();
ISugarQueryable<TResult> Select<TResult>(string select);
ISugarQueryable<T> Select(string select);
ISugarQueryable<T> MergeTable();

View File

@@ -41,6 +41,7 @@ namespace SqlSugar
IUpdateable<T> IgnoreColumns(bool ignoreAllNullColumns, bool isOffIdentity = false);
IUpdateable<T> IgnoreColumns(Expression<Func<T, object>> columns);
IUpdateable<T> IgnoreColumns(Func<string, bool> ignoreColumMethod);
IUpdateable<T> IsEnableUpdateVersionValidation();
IUpdateable<T> ReSetValue(Expression<Func<T, bool>> setValueExpression);
IUpdateable<T> RemoveDataCache();
KeyValuePair<string,List<SugarParameter>> ToSql();

View File

@@ -242,6 +242,16 @@ namespace SqlSugar
this.Context.Ado.ExecuteCommand(sql);
return true;
}
public override bool BackupTable(string oldTableName, string newTableName, int maxBackupDataRows = int.MaxValue)
{
oldTableName = this.SqlBuilder.GetTranslationTableName(oldTableName);
newTableName = this.SqlBuilder.GetTranslationTableName(newTableName);
string sql = string.Format(this.BackupTableSql, newTableName, oldTableName, maxBackupDataRows);
this.Context.Ado.ExecuteCommand(sql);
return true;
}
protected override string GetCreateTableSql(string tableName, List<DbColumnInfo> columns)
{
List<string> columnArray = new List<string>();

View File

@@ -2,7 +2,7 @@
<package >
<metadata>
<id>sqlSugarCore</id>
<version>4.7</version>
<version>4.8</version>
<authors>sunkaixuan</authors>
<owners>Landa</owners>
<licenseUrl>http://www.apache.org/licenses/LICENSE-2.0.html</licenseUrl>

View File

@@ -52,4 +52,9 @@ namespace SqlSugar
return string.Format("{0} '{1}' \r\n", key, value);
}
}
public class VersionExceptions : UtilExceptions
{
public VersionExceptions(string message)
: base(message){ }
}
}

View File

@@ -14,7 +14,7 @@ namespace SqlSugar
internal static Type GetUnderType(Type oldType)
{
Type type = Nullable.GetUnderlyingType(oldType);
return type==null ? oldType : type;
return type == null ? oldType : type;
}
internal static Type GetRootBaseType(Type entityType)
@@ -103,5 +103,16 @@ namespace SqlSugar
action();
return value;
}
internal static object DefaultForType(Type targetType)
{
return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
}
internal static Int64 GetLong(byte[] bytes)
{
return Convert.ToInt64(string.Join("", bytes).PadRight(20, '0'));
}
}
}