Synchronization code

This commit is contained in:
sunkaixuan
2025-02-13 14:09:23 +08:00
parent 26e6c213df
commit f1fedd9578
21 changed files with 198 additions and 28 deletions

View File

@@ -31,6 +31,7 @@ namespace SqlSugar
#endregion #endregion
#region Properties #region Properties
internal bool IsOpenAsync { get; set; }
protected List<IDataParameter> OutputParameters { get; set; } protected List<IDataParameter> OutputParameters { get; set; }
public virtual string SqlParameterKeyWord { get { return "@"; } } public virtual string SqlParameterKeyWord { get { return "@"; } }
public IDbTransaction Transaction { get; set; } public IDbTransaction Transaction { get; set; }
@@ -626,7 +627,7 @@ namespace SqlSugar
if (this.ProcessingEventStartingSQL != null) if (this.ProcessingEventStartingSQL != null)
ExecuteProcessingSQL(ref sql,ref parameters); ExecuteProcessingSQL(ref sql,ref parameters);
ExecuteBefore(sql, parameters); ExecuteBefore(sql, parameters);
var sqlCommand = GetCommand(sql, parameters); var sqlCommand =IsOpenAsync? await GetCommandAsync(sql, parameters) : GetCommand(sql, parameters);
int count; int count;
if (this.CancellationToken == null) if (this.CancellationToken == null)
count=await sqlCommand.ExecuteNonQueryAsync(); count=await sqlCommand.ExecuteNonQueryAsync();
@@ -668,7 +669,7 @@ namespace SqlSugar
if (this.ProcessingEventStartingSQL != null) if (this.ProcessingEventStartingSQL != null)
ExecuteProcessingSQL(ref sql,ref parameters); ExecuteProcessingSQL(ref sql,ref parameters);
ExecuteBefore(sql, parameters); ExecuteBefore(sql, parameters);
var sqlCommand = GetCommand(sql, parameters); var sqlCommand = IsOpenAsync ? await GetCommandAsync(sql, parameters) : GetCommand(sql, parameters);
DbDataReader sqlDataReader; DbDataReader sqlDataReader;
if(this.CancellationToken==null) if(this.CancellationToken==null)
sqlDataReader=await sqlCommand.ExecuteReaderAsync(this.IsAutoClose() ? CommandBehavior.CloseConnection : CommandBehavior.Default); sqlDataReader=await sqlCommand.ExecuteReaderAsync(this.IsAutoClose() ? CommandBehavior.CloseConnection : CommandBehavior.Default);
@@ -707,7 +708,7 @@ namespace SqlSugar
if (this.ProcessingEventStartingSQL != null) if (this.ProcessingEventStartingSQL != null)
ExecuteProcessingSQL(ref sql,ref parameters); ExecuteProcessingSQL(ref sql,ref parameters);
ExecuteBefore(sql, parameters); ExecuteBefore(sql, parameters);
var sqlCommand = GetCommand(sql, parameters); var sqlCommand = IsOpenAsync ? await GetCommandAsync(sql, parameters) : GetCommand(sql, parameters);
object scalar; object scalar;
if(CancellationToken==null) if(CancellationToken==null)
scalar=await sqlCommand.ExecuteScalarAsync(); scalar=await sqlCommand.ExecuteScalarAsync();
@@ -1461,6 +1462,11 @@ namespace SqlSugar
#endregion #endregion
#region Helper #region Helper
public virtual async Task<DbCommand> GetCommandAsync(string sql, SugarParameter[] parameters)
{
await Task.FromResult(0);
throw new NotImplementedException();
}
public async Task CloseAsync() public async Task CloseAsync()
{ {
if (this.Transaction != null) if (this.Transaction != null)

View File

@@ -200,7 +200,7 @@ namespace SqlSugar
var tempTableName = "TempDiff" + DateTime.Now.ToString("yyMMssHHmmssfff"); var tempTableName = "TempDiff" + DateTime.Now.ToString("yyMMssHHmmssfff");
var oldTableName = this.Context.EntityMaintenance.GetEntityInfo(type).DbTableName; var oldTableName = this.Context.EntityMaintenance.GetEntityInfo(type).DbTableName;
var db = new SqlSugarProvider(UtilMethods.CopyConfig(this.Context.CurrentConnectionConfig)); var db = new SqlSugarProvider(UtilMethods.CopyConfig(this.Context.CurrentConnectionConfig));
UtilMethods.IsNullReturnNew(db.CurrentConnectionConfig.ConfigureExternalServices); db.CurrentConnectionConfig.ConfigureExternalServices=UtilMethods.IsNullReturnNew(db.CurrentConnectionConfig.ConfigureExternalServices);
db.CurrentConnectionConfig.ConfigureExternalServices.EntityNameService += (x, p) => db.CurrentConnectionConfig.ConfigureExternalServices.EntityNameService += (x, p) =>
{ {
p.IsDisabledUpdateAll = true;//Disabled update p.IsDisabledUpdateAll = true;//Disabled update

View File

@@ -1,4 +1,5 @@
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Linq; using System.Linq;
@@ -214,12 +215,18 @@ namespace SqlSugar
{ {
return GetArrayList<T>(type, dataReader); return GetArrayList<T>(type, dataReader);
} }
else if (typeof(T)!=type&&typeof(T).IsInterface)
{
//这里是为了解决返回类型是接口的问题
return GetEntityListByType<T>(type, Context, dataReader);
}
else else
{ {
return GetEntityList<T>(Context, dataReader); return GetEntityList<T>(Context, dataReader);
} }
} }
} }
public virtual async Task<List<T>> DataReaderToListAsync<T>(Type type, IDataReader dataReader) public virtual async Task<List<T>> DataReaderToListAsync<T>(Type type, IDataReader dataReader)
{ {
using (dataReader) using (dataReader)
@@ -236,6 +243,11 @@ namespace SqlSugar
{ {
return await GetArrayListAsync<T>(type, dataReader); return await GetArrayListAsync<T>(type, dataReader);
} }
else if (typeof(T) != type && typeof(T).IsInterface)
{
//这里是为了解决返回类型是接口的问题
return await GetEntityListByTypeAsync<T>(type, Context, dataReader);
}
else else
{ {
return await GetEntityListAsync<T>(Context, dataReader); return await GetEntityListAsync<T>(Context, dataReader);
@@ -280,6 +292,37 @@ namespace SqlSugar
return GetEntityListAsync<T>(Context, dataReader); return GetEntityListAsync<T>(Context, dataReader);
} }
} }
public virtual List<T> GetEntityListByType<T>(Type entityType, SqlSugarProvider context, IDataReader dataReader)
{
var method = typeof(DbBindProvider).GetMethod("GetEntityList", BindingFlags.Instance | BindingFlags.NonPublic);
var genericMethod = method.MakeGenericMethod(entityType);
var objectValue= genericMethod.Invoke(this, new object[] { context, dataReader });
List<T> result = new List<T>();
foreach (var item in objectValue as IEnumerable)
{
result.Add((T)item);
}
return result;
}
public virtual async Task<List<T>> GetEntityListByTypeAsync<T>(Type entityType, SqlSugarProvider context, IDataReader dataReader)
{
var method = typeof(DbBindProvider).GetMethod("GetEntityListAsync", BindingFlags.Instance | BindingFlags.NonPublic);
var genericMethod = method.MakeGenericMethod(entityType);
Task task = (Task)genericMethod.Invoke(this, new object[] { context, dataReader });
return await GetTask<T>(task);
}
private static async Task<List<T>> GetTask<T>(Task task)
{
await task.ConfigureAwait(false); // 等待任务完成
var resultProperty = task.GetType().GetProperty("Result");
var value = resultProperty.GetValue(task);
List<T> result = new List<T>();
foreach (var item in value as IEnumerable)
{
result.Add((T)item);
}
return (List<T>)result;
}
#endregion #endregion
#region Throw rule #region Throw rule

View File

@@ -422,7 +422,13 @@ namespace SqlSugar
if (!column.EntityName.ObjToString().StartsWith("<>f__AnonymousType") if (!column.EntityName.ObjToString().StartsWith("<>f__AnonymousType")
&&column.PropertyInfo?.ReflectedType!=typeof(DbTableInfo)) &&column.PropertyInfo?.ReflectedType!=typeof(DbTableInfo))
{ {
var isOldOwnsOne = column.IsOwnsOne;
this.Context.CurrentConnectionConfig.ConfigureExternalServices.EntityService(property, column); this.Context.CurrentConnectionConfig.ConfigureExternalServices.EntityService(property, column);
if (column.IsOwnsOne == true && isOldOwnsOne == false)
{
SetValueObjectColumns(result, property, column);
continue;
}
} }
} }
if (column.PropertyInfo.DeclaringType != null if (column.PropertyInfo.DeclaringType != null

View File

@@ -741,6 +741,7 @@ namespace SqlSugar
foreach (var item in this.InsertObjs) foreach (var item in this.InsertObjs)
{ {
var insertable = this.Context.Insertable(item) var insertable = this.Context.Insertable(item)
.AS(this.InsertBuilder.AsName)
.InsertColumns(this.InsertBuilder.DbColumnInfoList.Select(it => it.DbColumnName).Distinct().ToArray()); .InsertColumns(this.InsertBuilder.DbColumnInfoList.Select(it => it.DbColumnName).Distinct().ToArray());
if (pkInfo.UnderType == UtilConstants.IntType) if (pkInfo.UnderType == UtilConstants.IntType)
{ {

View File

@@ -10,7 +10,7 @@ using System.Reflection;
using System.Dynamic; using System.Dynamic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
namespace SqlSugar namespace SqlSugar
{ {
@@ -853,6 +853,11 @@ namespace SqlSugar
} }
public virtual string ToSqlString() public virtual string ToSqlString()
{ {
if (this.EntityInfo?.Type?.IsInterface==true)
{
this.QueryBuilder.SelectValue = " * ";
this.AsType(this.EntityInfo.Type);
}
var sqlObj = this.Clone().ToSql(); var sqlObj = this.Clone().ToSql();
var result = sqlObj.Key; var result = sqlObj.Key;
if (result == null) return null; if (result == null) return null;

View File

@@ -1889,7 +1889,14 @@ namespace SqlSugar
SugarParameter[] parameters = sqlObj.Value.ToArray(); SugarParameter[] parameters = sqlObj.Value.ToArray();
var dataReader = this.Db.GetDataReader(sqlString, parameters); var dataReader = this.Db.GetDataReader(sqlString, parameters);
this.Db.GetDataBefore(sqlString, parameters); this.Db.GetDataBefore(sqlString, parameters);
result = GetData<TResult>(isComplexModel, entityType, dataReader); if (entityType.IsInterface)
{
result = GetData<TResult>(isComplexModel, this.QueryBuilder.AsType, dataReader);
}
else
{
result = GetData<TResult>(isComplexModel, entityType, dataReader);
}
this.Db.GetDataAfter(sqlString, parameters); this.Db.GetDataAfter(sqlString, parameters);
RestChangeMasterQuery(isChangeQueryableMasterSlave); RestChangeMasterQuery(isChangeQueryableMasterSlave);
RestChangeSlaveQuery(isChangeQueryableSlave); RestChangeSlaveQuery(isChangeQueryableSlave);
@@ -1906,7 +1913,14 @@ namespace SqlSugar
SugarParameter[] parameters = sqlObj.Value.ToArray(); SugarParameter[] parameters = sqlObj.Value.ToArray();
var dataReader = await this.Db.GetDataReaderAsync(sqlString, parameters); var dataReader = await this.Db.GetDataReaderAsync(sqlString, parameters);
this.Db.GetDataBefore(sqlString, parameters); this.Db.GetDataBefore(sqlString, parameters);
result = await GetDataAsync<TResult>(isComplexModel, entityType, dataReader); if (entityType.IsInterface)
{
result =await GetDataAsync<TResult>(isComplexModel, this.QueryBuilder.AsType, dataReader);
}
else
{
result = await GetDataAsync<TResult>(isComplexModel, entityType, dataReader);
}
this.Db.GetDataAfter(sqlString, parameters); this.Db.GetDataAfter(sqlString, parameters);
RestChangeMasterQuery(isChangeQueryableMasterSlave); RestChangeMasterQuery(isChangeQueryableMasterSlave);
RestChangeSlaveQuery(isChangeQueryableSlave); RestChangeSlaveQuery(isChangeQueryableSlave);
@@ -2110,6 +2124,7 @@ namespace SqlSugar
asyncQueryableBuilder.JoinExpression = this.QueryBuilder.JoinExpression; asyncQueryableBuilder.JoinExpression = this.QueryBuilder.JoinExpression;
asyncQueryableBuilder.WhereIndex = this.QueryBuilder.WhereIndex; asyncQueryableBuilder.WhereIndex = this.QueryBuilder.WhereIndex;
asyncQueryableBuilder.HavingInfos = this.QueryBuilder.HavingInfos; asyncQueryableBuilder.HavingInfos = this.QueryBuilder.HavingInfos;
asyncQueryableBuilder.AsType = this.QueryBuilder.AsType;
asyncQueryableBuilder.LambdaExpressions.ParameterIndex = this.QueryBuilder.LambdaExpressions.ParameterIndex; asyncQueryableBuilder.LambdaExpressions.ParameterIndex = this.QueryBuilder.LambdaExpressions.ParameterIndex;
asyncQueryableBuilder.IgnoreColumns = this.Context.Utilities.TranslateCopy(this.QueryBuilder.IgnoreColumns); asyncQueryableBuilder.IgnoreColumns = this.Context.Utilities.TranslateCopy(this.QueryBuilder.IgnoreColumns);
asyncQueryableBuilder.AsTables = this.Context.Utilities.TranslateCopy(this.QueryBuilder.AsTables); asyncQueryableBuilder.AsTables = this.Context.Utilities.TranslateCopy(this.QueryBuilder.AsTables);

View File

@@ -329,7 +329,7 @@ namespace SqlSugar
} }
public ISugarQueryable<T> Clone() public ISugarQueryable<T> Clone()
{ {
var queryable = this.Context.Queryable<object>().Select<T>().WithCacheIF(IsCache, CacheTime); var queryable = this.Context.Queryable<object>().AsType(this.QueryBuilder.AsType).Select<T>().WithCacheIF(IsCache, CacheTime);
CopyQueryBuilder(queryable.QueryBuilder); CopyQueryBuilder(queryable.QueryBuilder);
((QueryableProvider<T>)queryable).CacheKey = this.CacheKey; ((QueryableProvider<T>)queryable).CacheKey = this.CacheKey;
((QueryableProvider<T>)queryable).MapperAction = this.MapperAction; ((QueryableProvider<T>)queryable).MapperAction = this.MapperAction;
@@ -359,8 +359,18 @@ namespace SqlSugar
this.QueryBuilder.IsCrossQueryWithAttr = true; this.QueryBuilder.IsCrossQueryWithAttr = true;
return this.AS(asName); return this.AS(asName);
} }
public ISugarQueryable<Type> Cast<Type>()
{
var selectValue = this.Clone().QueryBuilder.GetSelectValue;
return this.Select<Type>().Select(selectValue);
}
public ISugarQueryable<T> AsType(Type tableNameType) public ISugarQueryable<T> AsType(Type tableNameType)
{ {
if (tableNameType == null)
{
return this;
}
this.QueryBuilder.AsType = tableNameType;
return AS(this.Context.EntityMaintenance.GetEntityInfo(tableNameType).DbTableName); return AS(this.Context.EntityMaintenance.GetEntityInfo(tableNameType).DbTableName);
} }
public virtual ISugarQueryable<T> With(string withString) public virtual ISugarQueryable<T> With(string withString)
@@ -1495,6 +1505,11 @@ namespace SqlSugar
} }
else if (this.QueryBuilder.EntityType == UtilConstants.ObjType || (this.QueryBuilder.AsTables != null && this.QueryBuilder.AsTables.Count == 1)||this.QueryBuilder.EntityName!=this.QueryBuilder.EntityType.Name) else if (this.QueryBuilder.EntityType == UtilConstants.ObjType || (this.QueryBuilder.AsTables != null && this.QueryBuilder.AsTables.Count == 1)||this.QueryBuilder.EntityName!=this.QueryBuilder.EntityType.Name)
{ {
if (typeof(TResult).IsInterface&&this.QueryBuilder.AsType==null)
{
Check.ExceptionEasy("Select< interface > requires a full example of AsType(type) db.Queryable<object>().AsType(type).Select<Interface>().ToList()"
, "Select<接口>需要AsType(type)完整示例db.Queryable<object>().AsType(type).Select<Interface>().ToList()");
}
if (this.QueryBuilder.SelectValue.HasValue()&& this.QueryBuilder.SelectValue.ObjToString().Contains("AS")) if (this.QueryBuilder.SelectValue.HasValue()&& this.QueryBuilder.SelectValue.ObjToString().Contains("AS"))
{ {
return this.Select<TResult>(this.QueryBuilder.SelectValue+""); return this.Select<TResult>(this.QueryBuilder.SelectValue+"");
@@ -1520,6 +1535,13 @@ namespace SqlSugar
} }
else else
{ {
if (typeof(TResult).IsInterface&& typeof(TResult).IsAssignableFrom(this.EntityInfo.Type))
{
if (!this.QueryBuilder.AsTables.Any())
{
this.AsType(this.EntityInfo.Type);
}
}
var selects = this.QueryBuilder.GetSelectValueByString(); var selects = this.QueryBuilder.GetSelectValueByString();
if (selects.ObjToString().ToLower().IsContainsIn(".","("," as ")) if (selects.ObjToString().ToLower().IsContainsIn(".","("," as "))
{ {

View File

@@ -280,7 +280,7 @@ namespace SqlSugar
} }
private int GetDbColumnIndex = 0; private int GetDbColumnIndex = 0;
public virtual string GetDbColumn(DbColumnInfo columnInfo ,object name) public virtual string GetDbColumn(DbColumnInfo columnInfo ,object name)
{ {
if (columnInfo.InsertServerTime) if (columnInfo.InsertServerTime)
{ {
@@ -296,11 +296,11 @@ namespace SqlSugar
} }
else if (columnInfo.InsertSql.HasValue()) else if (columnInfo.InsertSql.HasValue())
{ {
if (columnInfo.InsertSql.Contains("{0}")) if (columnInfo.InsertSql.Contains("{0}"))
{ {
if (columnInfo.Value == null) if (columnInfo.Value == null)
{ {
return string.Format(columnInfo.InsertSql, "null").Replace("'null'","null"); return string.Format(columnInfo.InsertSql, "null").Replace("'null'", "null");
} }
else else
{ {
@@ -309,7 +309,7 @@ namespace SqlSugar
} }
return columnInfo.InsertSql; return columnInfo.InsertSql;
} }
else if (columnInfo.SqlParameterDbType is Type && (Type)columnInfo.SqlParameterDbType == UtilConstants.SqlConvertType) else if (columnInfo.SqlParameterDbType is Type && IsNoParameterConvert(columnInfo))
{ {
var type = columnInfo.SqlParameterDbType as Type; var type = columnInfo.SqlParameterDbType as Type;
var ParameterConverter = type.GetMethod("ParameterConverter").MakeGenericMethod(typeof(string)); var ParameterConverter = type.GetMethod("ParameterConverter").MakeGenericMethod(typeof(string));
@@ -319,17 +319,17 @@ namespace SqlSugar
} }
else if (columnInfo.SqlParameterDbType is Type) else if (columnInfo.SqlParameterDbType is Type)
{ {
var type=columnInfo.SqlParameterDbType as Type; var type = columnInfo.SqlParameterDbType as Type;
var ParameterConverter=type.GetMethod("ParameterConverter").MakeGenericMethod(columnInfo.PropertyType); var ParameterConverter = type.GetMethod("ParameterConverter").MakeGenericMethod(columnInfo.PropertyType);
var obj=Activator.CreateInstance(type); var obj = Activator.CreateInstance(type);
var p = ParameterConverter.Invoke(obj,new object[] {columnInfo.Value, GetDbColumnIndex }) as SugarParameter; var p = ParameterConverter.Invoke(obj, new object[] { columnInfo.Value, GetDbColumnIndex }) as SugarParameter;
GetDbColumnIndex++; GetDbColumnIndex++;
//this.Parameters.RemoveAll(it => it.ParameterName == it.ParameterName); //this.Parameters.RemoveAll(it => it.ParameterName == it.ParameterName);
UtilMethods.ConvertParameter(p,this.Builder); UtilMethods.ConvertParameter(p, this.Builder);
this.Parameters.Add(p); this.Parameters.Add(p);
return p.ParameterName; return p.ParameterName;
} }
else if (columnInfo.DataType?.Equals("nvarchar2")==true) else if (columnInfo.DataType?.Equals("nvarchar2") == true)
{ {
var pname = Builder.SqlParameterKeyWord + columnInfo.DbColumnName + "_ts" + GetDbColumnIndex; var pname = Builder.SqlParameterKeyWord + columnInfo.DbColumnName + "_ts" + GetDbColumnIndex;
var p = new SugarParameter(pname, columnInfo.Value); var p = new SugarParameter(pname, columnInfo.Value);
@@ -338,7 +338,7 @@ namespace SqlSugar
GetDbColumnIndex++; GetDbColumnIndex++;
return pname; return pname;
} }
else if (columnInfo.PropertyType!=null&&columnInfo.PropertyType.Name == "TimeOnly" ) else if (columnInfo.PropertyType != null && columnInfo.PropertyType.Name == "TimeOnly")
{ {
var timeSpan = UtilMethods.TimeOnlyToTimeSpan(columnInfo.Value); var timeSpan = UtilMethods.TimeOnlyToTimeSpan(columnInfo.Value);
var pname = Builder.SqlParameterKeyWord + columnInfo.DbColumnName + "_ts" + GetDbColumnIndex; var pname = Builder.SqlParameterKeyWord + columnInfo.DbColumnName + "_ts" + GetDbColumnIndex;
@@ -352,7 +352,7 @@ namespace SqlSugar
var pname = Builder.SqlParameterKeyWord + columnInfo.DbColumnName + "_ts" + GetDbColumnIndex; var pname = Builder.SqlParameterKeyWord + columnInfo.DbColumnName + "_ts" + GetDbColumnIndex;
if (timeSpan == null) if (timeSpan == null)
{ {
this.Parameters.Add(new SugarParameter(pname, null) { DbType=System.Data.DbType.Date }); this.Parameters.Add(new SugarParameter(pname, null) { DbType = System.Data.DbType.Date });
} }
else else
{ {
@@ -376,6 +376,19 @@ namespace SqlSugar
} }
} }
private static bool IsNoParameterConvert(DbColumnInfo columnInfo)
{
if (columnInfo.SqlParameterDbType is Type t)
{
var isAssignableFrom = typeof(DbConvert.NoParameterCommonPropertyConvert).IsAssignableFrom(t);
if (isAssignableFrom)
{
return isAssignableFrom;
}
}
return (Type)columnInfo.SqlParameterDbType == UtilConstants.SqlConvertType;
}
#endregion #endregion
} }
} }

View File

@@ -33,7 +33,8 @@ namespace SqlSugar
public ISqlBuilder Builder { get; set; } public ISqlBuilder Builder { get; set; }
#endregion #endregion
#region Splicing basic #region Splicing basic
public Type AsType { get; set; }
public bool IsParameterizedConstructor { get; set; } public bool IsParameterizedConstructor { get; set; }
public string Hints { get; set; } public string Hints { get; set; }
internal AppendNavInfo AppendNavInfo { get; set; } internal AppendNavInfo AppendNavInfo { get; set; }

View File

@@ -31,11 +31,11 @@ namespace SqlSugar
#region abstract Methods #region abstract Methods
public virtual bool SupportReadToken { get; set; } public virtual bool SupportReadToken { get; set; } = true;
public virtual Task<bool> GetReaderByToken(IDataReader dataReader, CancellationToken cancellationToken) public virtual Task<bool> GetReaderByToken(IDataReader dataReader, CancellationToken cancellationToken)
{ {
return ((DbDataReader)dataReader).ReadAsync(); return ((DbDataReader)dataReader).ReadAsync(cancellationToken);
} }
public virtual void ChangeJsonType(SugarParameter paramter) public virtual void ChangeJsonType(SugarParameter paramter)
{ {

View File

@@ -458,11 +458,11 @@ namespace SqlSugar
{ {
return LambdaExpressions.DbMehtods.GetDate(); return LambdaExpressions.DbMehtods.GetDate();
} }
else if (columnInfo.PropertyType.FullName == "NetTopologySuite.Geometries.Geometry") else if (columnInfo.PropertyType.FullName == "NetTopologySuite.Geometries.Geometry")
{ {
var pname = Builder.SqlParameterKeyWord + "Geometry" + GetDbColumnIndex; var pname = Builder.SqlParameterKeyWord + "Geometry" + GetDbColumnIndex;
var p = new SugarParameter(pname, columnInfo.Value); var p = new SugarParameter(pname, columnInfo.Value);
p.DbType= System.Data.DbType.Object; p.DbType = System.Data.DbType.Object;
this.Parameters.Add(p); this.Parameters.Add(p);
GetDbColumnIndex++; GetDbColumnIndex++;
return pname; return pname;
@@ -501,7 +501,7 @@ namespace SqlSugar
} }
return columnInfo.UpdateSql; return columnInfo.UpdateSql;
} }
else if (columnInfo.SqlParameterDbType is Type && (Type)columnInfo.SqlParameterDbType == UtilConstants.SqlConvertType) else if (columnInfo.SqlParameterDbType is Type && IsNoParameterConvert(columnInfo))
{ {
var type = columnInfo.SqlParameterDbType as Type; var type = columnInfo.SqlParameterDbType as Type;
var ParameterConverter = type.GetMethod("ParameterConverter").MakeGenericMethod(typeof(string)); var ParameterConverter = type.GetMethod("ParameterConverter").MakeGenericMethod(typeof(string));
@@ -564,6 +564,20 @@ namespace SqlSugar
return name + ""; return name + "";
} }
} }
private static bool IsNoParameterConvert(DbColumnInfo columnInfo)
{
if (columnInfo.SqlParameterDbType is Type t)
{
var isAssignableFrom = typeof(DbConvert.NoParameterCommonPropertyConvert).IsAssignableFrom(t);
if (isAssignableFrom)
{
return isAssignableFrom;
}
}
return (Type)columnInfo.SqlParameterDbType == UtilConstants.SqlConvertType;
}
private bool IsSingleSetExp(DbColumnInfo columnInfo) private bool IsSingleSetExp(DbColumnInfo columnInfo)
{ {
return this.ReSetValueBySqlExpList != null && return this.ReSetValueBySqlExpList != null &&

View File

@@ -881,6 +881,10 @@ namespace SqlSugar
{ {
return UtilMethods.CountSubstringOccurrences(sql,"WHERE")>1; return UtilMethods.CountSubstringOccurrences(sql,"WHERE")>1;
} }
private bool IsCorrectErrorSqlParameterName()
{
return this.Context?.CurrentConnectionConfig?.MoreSettings?.IsCorrectErrorSqlParameterName == true;
}
private void ThrowUpdateByExpression() private void ThrowUpdateByExpression()
{ {

View File

@@ -860,6 +860,10 @@ namespace SqlSugar
UpdateBuilder.LambdaExpressions.ParameterIndex = 100; UpdateBuilder.LambdaExpressions.ParameterIndex = 100;
} }
var expResult = UpdateBuilder.GetExpressionValue(columns, ResolveExpressType.WhereSingle).GetResultString().Replace(")", " )").Replace("(", "( ").Trim().TrimStart('(').TrimEnd(')').Replace("= =","="); var expResult = UpdateBuilder.GetExpressionValue(columns, ResolveExpressType.WhereSingle).GetResultString().Replace(")", " )").Replace("(", "( ").Trim().TrimStart('(').TrimEnd(')').Replace("= =","=");
if (IsCorrectErrorSqlParameterName())
{
expResult = UpdateBuilder.GetExpressionValue(binaryExp.Right, ResolveExpressType.WhereSingle).GetResultString().Trim();
}
if (expResult.EndsWith(" IS NULL ")) if (expResult.EndsWith(" IS NULL "))
{ {
expResult = Regex.Split(expResult, " IS NULL ")[0]+" = NULL "; expResult = Regex.Split(expResult, " IS NULL ")[0]+" = NULL ";
@@ -869,7 +873,11 @@ namespace SqlSugar
expResult = Regex.Split(expResult, "IS NULL ")[0] + " = NULL "; expResult = Regex.Split(expResult, "IS NULL ")[0] + " = NULL ";
} }
string key = SqlBuilder.GetNoTranslationColumnName(expResult); string key = SqlBuilder.GetNoTranslationColumnName(expResult);
if (IsCorrectErrorSqlParameterName()&& binaryExp.Left is MemberExpression member)
{
key =this.EntityInfo.Columns.First(it=>it.PropertyName== member.Member.Name).DbColumnName;
expResult = $" {this.SqlBuilder.GetTranslationColumnName(key)}={expResult} ";
}
if (EntityInfo.Columns.Where(it=>it.IsJson||it.IsTranscoding).Any(it => it.DbColumnName.EqualCase(key) || it.PropertyName.EqualCase(key))) if (EntityInfo.Columns.Where(it=>it.IsJson||it.IsTranscoding).Any(it => it.DbColumnName.EqualCase(key) || it.PropertyName.EqualCase(key)))
{ {
CheckTranscodeing(); CheckTranscodeing();

View File

@@ -426,6 +426,11 @@ namespace SqlSugar
var parameter = model.Args[0]; var parameter = model.Args[0];
return string.Format("COUNT(DISTINCT {0} )", parameter.MemberName); return string.Format("COUNT(DISTINCT {0} )", parameter.MemberName);
} }
public virtual string AggregateDistinctSum(MethodCallExpressionModel model)
{
var parameter = model.Args[0];
return string.Format("SUM(DISTINCT {0} )", parameter.MemberName);
}
public virtual string MappingColumn(MethodCallExpressionModel model) public virtual string MappingColumn(MethodCallExpressionModel model)
{ {
@@ -1195,7 +1200,12 @@ namespace SqlSugar
{ {
return $" uuid_generate_v4() "; return $" uuid_generate_v4() ";
} }
public virtual string Coalesce(MethodCallExpressionModel mode)
{
var parameterNameA = mode.Args[0].MemberName;
var parameterNameB = mode.Args[1].MemberName;
return $" COALESCE({parameterNameA},{parameterNameB}) ";
}
public virtual string FullTextContains(MethodCallExpressionModel mode) public virtual string FullTextContains(MethodCallExpressionModel mode)
{ {
var columns = mode.Args[0].MemberName; var columns = mode.Args[0].MemberName;

View File

@@ -54,6 +54,7 @@ namespace SqlSugar
string AggregateMax(MethodCallExpressionModel model); string AggregateMax(MethodCallExpressionModel model);
string AggregateCount(MethodCallExpressionModel model); string AggregateCount(MethodCallExpressionModel model);
string AggregateDistinctCount(MethodCallExpressionModel model); string AggregateDistinctCount(MethodCallExpressionModel model);
string AggregateDistinctSum(MethodCallExpressionModel model);
string MappingColumn(MethodCallExpressionModel model); string MappingColumn(MethodCallExpressionModel model);
string IsNull(MethodCallExpressionModel model); string IsNull(MethodCallExpressionModel model);
string GetSelfAndAutoFill(string shortName,bool isSingle); string GetSelfAndAutoFill(string shortName,bool isSingle);
@@ -129,5 +130,6 @@ namespace SqlSugar
string FullTextContains(MethodCallExpressionModel mode); string FullTextContains(MethodCallExpressionModel mode);
string PgsqlArrayContains(MethodCallExpressionModel model); string PgsqlArrayContains(MethodCallExpressionModel model);
string SelectFields(MethodCallExpressionModel model); string SelectFields(MethodCallExpressionModel model);
string Coalesce(MethodCallExpressionModel model);
} }
} }

View File

@@ -10,6 +10,11 @@ namespace SqlSugar
{ {
public partial class SqlFunc public partial class SqlFunc
{ {
public static T Coalesce<T>(T value1, T value2)
{
throw new NotSupportedException("Can only be used in expressions");
}
public static bool FullTextContains(string [] columnNames, string keyword) public static bool FullTextContains(string [] columnNames, string keyword)
{ {
throw new NotSupportedException("Can only be used in expressions"); throw new NotSupportedException("Can only be used in expressions");
@@ -360,6 +365,7 @@ namespace SqlSugar
public static TResult AggregateMax<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<TResult>(TResult 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 int AggregateDistinctCount<TResult>(TResult thisValue) { throw new NotSupportedException("Can only be used in expressions"); } public static int AggregateDistinctCount<TResult>(TResult thisValue) { throw new NotSupportedException("Can only be used in expressions"); }
public static int AggregateDistinctSum<TResult>(TResult thisValue) { throw new NotSupportedException("Can only be used in expressions"); }
public static TResult MappingColumn<TResult>(TResult type,string newColumnName) { throw new NotSupportedException("Can only be used in expressions"); } public static TResult MappingColumn<TResult>(TResult type,string newColumnName) { throw new NotSupportedException("Can only be used in expressions"); }
public static TResult MappingColumn<TResult>(string newColumnName) { throw new NotSupportedException("Can only be used in expressions"); } public static TResult MappingColumn<TResult>(string newColumnName) { throw new NotSupportedException("Can only be used in expressions"); }
/// <summary> /// <summary>

View File

@@ -626,6 +626,7 @@ namespace SqlSugar
} }
var result = this.Context.DbMehtods.DateValue(new MethodCallExpressionModel() var result = this.Context.DbMehtods.DateValue(new MethodCallExpressionModel()
{ {
Conext=this.Context,
Args = new List<MethodCallExpressionArgs>() { Args = new List<MethodCallExpressionArgs>() {
new MethodCallExpressionArgs() { IsMember = !isConst, MemberName = parameter.CommonTempData, MemberValue = null }, new MethodCallExpressionArgs() { IsMember = !isConst, MemberName = parameter.CommonTempData, MemberValue = null },
new MethodCallExpressionArgs() { IsMember = true, MemberName = name, MemberValue = name } new MethodCallExpressionArgs() { IsMember = true, MemberName = name, MemberValue = name }
@@ -795,6 +796,10 @@ namespace SqlSugar
fieldName = fieldName.Replace(UtilConstants.Space, guid); fieldName = fieldName.Replace(UtilConstants.Space, guid);
} }
fieldName = Context.GetTranslationColumnName(fieldName); fieldName = Context.GetTranslationColumnName(fieldName);
if (this.Context?.SugarContext?.Context?.CurrentConnectionConfig?.MoreSettings?.IsCorrectErrorSqlParameterName == true&& fieldName?.Contains(ExpressionConst.LeftParenthesis)==true)
{
fieldName = Context.GetTranslationText(fieldName);
}
if (isSpace) if (isSpace)
{ {
fieldName = fieldName.Replace(guid, UtilConstants.Space); fieldName = fieldName.Replace(guid, UtilConstants.Space);

View File

@@ -870,6 +870,10 @@ namespace SqlSugar
} }
return result1; return result1;
case "GetDate": case "GetDate":
if (this.Context?.SugarContext?.Context?.CurrentConnectionConfig?.MoreSettings?.DatabaseModel == DbType.SqlServer)
{
return "GetDate()";
}
return this.Context.DbMehtods.GetDate(); return this.Context.DbMehtods.GetDate();
case "GetRandom": case "GetRandom":
return this.Context.DbMehtods.GetRandom(); return this.Context.DbMehtods.GetRandom();

View File

@@ -45,6 +45,10 @@ namespace SqlSugar
{ {
return new MySqlQueryable<T>(); return new MySqlQueryable<T>();
} }
else if (currentConnectionConfig.DbType == DbType.Sqlite)
{
return new SqliteQueryable<T>();
}
else if (currentConnectionConfig.DbType == DbType.PostgreSQL) else if (currentConnectionConfig.DbType == DbType.PostgreSQL)
{ {
return new PostgreSQLQueryable<T>(); return new PostgreSQLQueryable<T>();

View File

@@ -22,6 +22,7 @@ namespace SqlSugar
ISugarQueryable<T> AS(string tableName); ISugarQueryable<T> AS(string tableName);
ISugarQueryable<T> AsWithAttr(); ISugarQueryable<T> AsWithAttr();
ISugarQueryable<T> AsType(Type tableNameType); ISugarQueryable<T> AsType(Type tableNameType);
ISugarQueryable<Type> Cast<Type>();
ISugarQueryable<T> With(string withString); ISugarQueryable<T> With(string withString);
//ISugarQueryable<T> CrossQueryWithAttr(); //ISugarQueryable<T> CrossQueryWithAttr();
ISugarQueryable<T> CrossQuery<Type>(string configId); ISugarQueryable<T> CrossQuery<Type>(string configId);