void SqlMapper.ITypeMapRegistry.SetTypeMap(Type type, SqlMapper.ITypeMap map) { SetTable(type, map as Table); }
private IEnumerable<Location> FindLocations(SqlMapper.GridReader multi) { var locations = multi.Read<Location>(); var sales = multi.Read<SaleInstance>(); foreach (var location in locations) location.Sales = sales.Where(s => s.SaleId == location.SaleId).ToList(); return locations; }
public void AddParameters(IDbCommand command, SqlMapper.Identity identity) { var sqlCommand = (SqlCommand)command; var param = new SqlParameter(Name, TableValue) { TypeName = TableType, SqlDbType = SqlDbType.Structured, Direction = ParameterDirection.Input }; sqlCommand.Parameters.Add(param); }
private static void AddParameters(IDbCommand command, SqlMapper.Identity identity, object parameters) { var paramInfoGenerator = ParamInfoGenerators.GetOrAdd(parameters.GetType(), type => { var index = identity.ForDynamicParameters(type); return SqlMapper.CreateParamInfoGenerator(index, true, true); }); paramInfoGenerator(command, parameters); }
void SqlMapper.IDynamicParameters.AddParameters(IDbCommand command, SqlMapper.Identity identity) { foreach (var parameter in parameters) { var dbDataParameter = command.CreateParameter(); dbDataParameter.ParameterName = Clean(parameter.Name); dbDataParameter.Value = parameter.Value ?? DBNull.Value; dbDataParameter.Direction = ParameterDirection.Input; if (parameter.DbType.HasValue) dbDataParameter.DbType = parameter.DbType.Value; dbDataParameter.Size = parameter.Size ?? 0; command.Parameters.Add(dbDataParameter); } }
public void AddParameters(IDbCommand command, SqlMapper.Identity identity) { var sqlCommand = (SqlCommand)command; sqlCommand.CommandType = CommandType.Text; // Add the table parameter. var tableParam = sqlCommand.Parameters.Add(_tableValuedParam, SqlDbType.Structured); tableParam.TypeName = _tableValuedTypeName; tableParam.Value = GenerateTableParameterRecords(); // Add other additional parameters foreach (var param in _otherParams) { sqlCommand.Parameters.Add(param); } }
public void AddParameters(IDbCommand command, SqlMapper.Identity identity) { if (_parameters != null) { AddParameters(command, identity, _parameters); } foreach (var table in _tables) { var parameter = command.CreateParameter(); parameter.ParameterName = table.TableName; parameter.Value = table; command.Parameters.Add(parameter); } }
void SqlMapper.IDynamicParameters.AddParameters(IDbCommand command, SqlMapper.Identity identity) { foreach (var parameter in parameters) { var dbDataParameter = command.CreateParameter(); dbDataParameter.ParameterName = Clean(parameter.Name); dbDataParameter.Value = parameter.Value ?? DBNull.Value; dbDataParameter.Direction = ParameterDirection.Input; // Size is set implicitly by setting Value, see https://msdn.microsoft.com/en-us/library/system.data.common.dbparameter.size(v=vs.110).aspx // DbType is inferred too, but can be overriden for some columns if (parameter.DbType.HasValue) { dbDataParameter.DbType = parameter.DbType.Value; } command.Parameters.Add(dbDataParameter); } }
/// <summary> /// Creates a new <see cref="HistoryStatusCountsRecord"/> by reading from the given multi-mapped reader. /// </summary> /// <param name="multi">The multi-mapped reader to read from.</param> /// <returns>A new <see cref="HistoryStatusCountsRecord"/>.</returns> private static HistoryStatusCountsRecord CreateHistoryStatusCounts(SqlMapper.GridReader multi) { return new HistoryStatusCountsRecord() { TotalCount = multi.Read<long>().First(), SucceededCount = multi.Read<long>().First(), FailedCount = multi.Read<long>().First(), CanceledCount = multi.Read<long>().First(), TimedOutCount = multi.Read<long>().First(), InterruptedCount = multi.Read<long>().First() }; }
public static IDataReader ExecuteReader(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null) { TRACE(sql); return(SqlMapper.ExecuteReader(cnn, sql, param, transaction, commandTimeout, commandType)); }
public static Task <IEnumerable <object> > QueryAsync(this IDbConnection cnn, Type type, string sql, object param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null) { TRACE(sql); return(SqlMapper.QueryAsync(cnn, type, sql, param, transaction = null, commandTimeout, commandType)); }
public override void AddParameters(IDbCommand command, SqlMapper.Identity identity) { ResetCachedWhereClause(); if (_templates != null) { foreach (var template in _templates) { var newIdent = identity.ForDynamicParameters(template.GetType()); Action<IDbCommand, object> appender; lock (ParamReaderCache) { if (!ParamReaderCache.TryGetValue(newIdent, out appender)) { appender = SqlMapper.CreateParamInfoGenerator(newIdent, false, false); ParamReaderCache[newIdent] = appender; } } appender(command, template); } } foreach (var param in Parameters) { var name = param.Key; var add = !((SqlCommand)command).Parameters.Contains(name); SqlParameter p; if (add) { p = ((SqlCommand)command).CreateParameter(); p.ParameterName = name; } else { p = ((SqlCommand)command).Parameters[name]; } var val = param.Value.Value; p.Value = val ?? DBNull.Value; p.Direction = param.Value.ParameterDirection; var s = val as string; if (s != null) { if (s.Length <= 4000) p.Size = 4000; } if (param.Value.Size != null) { p.Size = param.Value.Size.Value; } p.DbType = (DbType)param.Value.TargetDatabaseType; if (add) command.Parameters.Add(p); param.Value.AttachedParameter = p; } }
public static Task <GridReader> QueryMultipleAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null) { TRACE(sql); return(SqlMapper.QueryMultipleAsync(cnn, sql, param, transaction, commandTimeout, commandType)); }
public IEnumerable <T> Query <T>(string sql, dynamic param = null, bool buffered = true) { return(SqlMapper.Query <T>(connection, sql, param as object, transaction, buffered, commandTimeout)); }
public IEnumerable <dynamic> Query(string sql, dynamic param = null, bool buffered = true) { return(SqlMapper.Query(connection, sql, param as object, transaction, buffered)); }
public static Task <IEnumerable <TReturn> > QueryAsync <TFirst, TSecond, TReturn>(this IDbConnection cnn, string sql, Func <TFirst, TSecond, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int?commandTimeout = null, CommandType?commandType = null) { TRACE(sql); return(SqlMapper.QueryAsync <TFirst, TSecond, TReturn>(cnn, sql, map, param, transaction, buffered, splitOn, commandTimeout, commandType)); }
//[return: Dynamic(new[] { false, true })] public static IEnumerable <dynamic> Query(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int?commandTimeout = null, CommandType?commandType = null) { TRACE(sql); return(SqlMapper.Query(cnn, sql, param, transaction, buffered, commandTimeout, commandType)); }
public static IEnumerable <TReturn> Query <TReturn>(this IDbConnection cnn, string sql, Type[] types, Func <object[], TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int?commandTimeout = null, CommandType?commandType = null) { TRACE(sql); return(SqlMapper.Query <TReturn>(cnn, sql, types, map, param, transaction, buffered, splitOn, commandTimeout, commandType)); }
public static List <T> AsList <T>(this IEnumerable <T> source) { return(SqlMapper.AsList(source)); }
public static Task <object> ExecuteScalarAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null) { TRACE(sql); return(SqlMapper.ExecuteScalarAsync(cnn, sql, param, transaction, commandTimeout, commandType)); }
/// <summary> /// Queries the multiple async. /// </summary> /// <returns>The multiple async.</returns> /// <param name="sql">Sql.</param> /// <param name="param">Parameter.</param> /// <param name="transaction">Transaction.</param> /// <param name="commandTimeout">Command timeout.</param> /// <param name="commandType">Command type.</param> public Task <SqlMapper.GridReader> QueryMultipleAsync(string sql, dynamic param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null) { return(SqlMapper.QueryMultipleAsync(connection, sql, param, transaction, commandTimeout, commandType)); }
public int Execute(string sql, dynamic param = null) { return(SqlMapper.Execute(connection, sql, param as object, transaction, commandTimeout: this.commandTimeout)); }
/// <summary> /// Execute a command that returns multiple result sets, and access each in turn. /// </summary> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> public SqlMapper.GridReader QueryMultiple(string sql, dynamic param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null) => SqlMapper.QueryMultiple(_connection, sql, param, transaction, commandTimeout, commandType);
public IEnumerable <TReturn> Query <TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(string sql, Func <TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int?commandTimeout = null) { return(SqlMapper.Query(connection, sql, map, param as object, transaction, buffered, splitOn)); }
//[return: Dynamic] public static dynamic QuerySingle(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null) { TRACE(sql); return(SqlMapper.QuerySingle(cnn, sql, param, transaction, commandTimeout, commandType)); }
public override void AddParameters(IDbCommand command, SqlMapper.Identity identity) { throw new NotImplementedException(); }
/// <summary> /// Add all the parameters needed to the command just before it executes /// </summary> /// <param name="command">The raw command prior to execution</param> /// <param name="identity">Information about the query</param> protected void AddParameters(IDbCommand command, SqlMapper.Identity identity) { var literals = SqlMapper.GetLiteralTokens(identity.sql); if (templates != null) { foreach (var template in templates) { var newIdent = identity.ForDynamicParameters(template.GetType()); Action <IDbCommand, object> appender; lock (paramReaderCache) { if (!paramReaderCache.TryGetValue(newIdent, out appender)) { appender = SqlMapper.CreateParamInfoGenerator(newIdent, true, RemoveUnused, literals); paramReaderCache[newIdent] = appender; } } appender(command, template); } // The parameters were added to the command, but not the // DynamicParameters until now. foreach (IDbDataParameter param in command.Parameters) { // If someone makes a DynamicParameters with a template, // then explicitly adds a parameter of a matching name, // it will already exist in 'parameters'. if (!parameters.ContainsKey(param.ParameterName)) { parameters.Add(param.ParameterName, new ParamInfo { AttachedParam = param, CameFromTemplate = true, DbType = param.DbType, Name = param.ParameterName, ParameterDirection = param.Direction, Size = param.Size, Value = param.Value }); } } // Now that the parameters are added to the command, let's place our output callbacks var tmp = outputCallbacks; if (tmp != null) { foreach (var generator in tmp) { generator(); } } } foreach (var param in parameters.Values) { if (param.CameFromTemplate) { continue; } var dbType = param.DbType; var val = param.Value; string name = Clean(param.Name); var isCustomQueryParameter = val is SqlMapper.ICustomQueryParameter; SqlMapper.ITypeHandler handler = null; if (dbType == null && val != null && !isCustomQueryParameter) { #pragma warning disable 618 dbType = SqlMapper.LookupDbType(val.GetType(), name, true, out handler); #pragma warning disable 618 } if (isCustomQueryParameter) { ((SqlMapper.ICustomQueryParameter)val).AddParameter(command, name); } else if (dbType == EnumerableMultiParameter) { #pragma warning disable 612, 618 SqlMapper.PackListParameters(command, name, val); #pragma warning restore 612, 618 } else { bool add = !command.Parameters.Contains(name); IDbDataParameter p; if (add) { p = command.CreateParameter(); p.ParameterName = name; } else { p = (IDbDataParameter)command.Parameters[name]; } p.Direction = param.ParameterDirection; if (handler == null) { #pragma warning disable 0618 p.Value = SqlMapper.SanitizeParameterValue(val); #pragma warning restore 0618 if (dbType != null && p.DbType != dbType) { p.DbType = dbType.Value; } var s = val as string; if (s?.Length <= DbString.DefaultLength) { p.Size = DbString.DefaultLength; } if (param.Size != null) { p.Size = param.Size.Value; } if (param.Precision != null) { p.Precision = param.Precision.Value; } if (param.Scale != null) { p.Scale = param.Scale.Value; } } else { if (dbType != null) { p.DbType = dbType.Value; } if (param.Size != null) { p.Size = param.Size.Value; } if (param.Precision != null) { p.Precision = param.Precision.Value; } if (param.Scale != null) { p.Scale = param.Scale.Value; } handler.SetValue(p, val ?? DBNull.Value); } if (add) { command.Parameters.Add(p); } param.AttachedParam = p; } } // note: most non-priveleged implementations would use: this.ReplaceLiterals(command); if (literals.Count != 0) { SqlMapper.ReplaceLiterals(this, command, literals); } }
/// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="identity"></param> void SqlMapper.IDynamicParameters.AddParameters(IDbCommand command, SqlMapper.Identity identity) { AddParameters(command, identity); }
/// <summary> /// Allows you to automatically populate a target property/field from output parameters. It actually /// creates an InputOutput parameter, so you can still pass data in. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target">The object whose property/field you wish to populate.</param> /// <param name="expression">A MemberExpression targeting a property/field of the target (or descendant thereof.)</param> /// <param name="dbType"></param> /// <param name="size">The size to set on the parameter. Defaults to 0, or DbString.DefaultLength in case of strings.</param> /// <returns>The DynamicParameters instance</returns> public DynamicParameters Output <T>(T target, Expression <Func <T, object> > expression, DbType?dbType = null, int?size = null) { var failMessage = "Expression must be a property/field chain off of a(n) {0} instance"; failMessage = string.Format(failMessage, typeof(T).Name); Action @throw = () => throw new InvalidOperationException(failMessage); // Is it even a MemberExpression? var lastMemberAccess = expression.Body as MemberExpression; if (lastMemberAccess == null || (!(lastMemberAccess.Member is PropertyInfo) && !(lastMemberAccess.Member is FieldInfo))) { if (expression.Body.NodeType == ExpressionType.Convert && expression.Body.Type == typeof(object) && ((UnaryExpression)expression.Body).Operand is MemberExpression) { // It's got to be unboxed lastMemberAccess = (MemberExpression)((UnaryExpression)expression.Body).Operand; } else { @throw(); } } // Does the chain consist of MemberExpressions leading to a ParameterExpression of type T? MemberExpression diving = lastMemberAccess; // Retain a list of member names and the member expressions so we can rebuild the chain. List <string> names = new List <string>(); List <MemberExpression> chain = new List <MemberExpression>(); do { // Insert the names in the right order so expression // "Post.Author.Name" becomes parameter "PostAuthorName" names.Insert(0, diving?.Member.Name); chain.Insert(0, diving); var constant = diving?.Expression as ParameterExpression; diving = diving?.Expression as MemberExpression; if (constant != null && constant.Type == typeof(T)) { break; } else if (diving == null || (!(diving.Member is PropertyInfo) && !(diving.Member is FieldInfo))) { @throw(); } }while (diving != null); var dynamicParamName = string.Concat(names.ToArray()); // Before we get all emitty... var lookup = string.Join("|", names.ToArray()); var cache = CachedOutputSetters <T> .Cache; var setter = (Action <object, DynamicParameters>)cache[lookup]; if (setter != null) { goto MAKECALLBACK; } // Come on let's build a method, let's build it, let's build it now! var dm = new DynamicMethod("ExpressionParam" + Guid.NewGuid().ToString(), null, new[] { typeof(object), GetType() }, true); var il = dm.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); // [object] il.Emit(OpCodes.Castclass, typeof(T)); // [T] // Count - 1 to skip the last member access for (var i = 0; i < chain.Count - 1; i++) { var member = chain[i].Member; if (member is PropertyInfo) { var get = ((PropertyInfo)member).GetGetMethod(true); il.Emit(OpCodes.Callvirt, get); // [Member{i}] } else // Else it must be a field! { il.Emit(OpCodes.Ldfld, (FieldInfo)member); // [Member{i}] } } var paramGetter = GetType().GetMethod("Get", new Type[] { typeof(string) }).MakeGenericMethod(lastMemberAccess.Type); il.Emit(OpCodes.Ldarg_1); // [target] [DynamicParameters] il.Emit(OpCodes.Ldstr, dynamicParamName); // [target] [DynamicParameters] [ParamName] il.Emit(OpCodes.Callvirt, paramGetter); // [target] [value], it's already typed thanks to generic method // GET READY var lastMember = lastMemberAccess.Member; if (lastMember is PropertyInfo) { var set = ((PropertyInfo)lastMember).GetSetMethod(true); il.Emit(OpCodes.Callvirt, set); // SET } else { il.Emit(OpCodes.Stfld, (FieldInfo)lastMember); // SET } il.Emit(OpCodes.Ret); // GO setter = (Action <object, DynamicParameters>)dm.CreateDelegate(typeof(Action <object, DynamicParameters>)); lock (cache) { cache[lookup] = setter; } // Queue the preparation to be fired off when adding parameters to the DbCommand MAKECALLBACK: (outputCallbacks ?? (outputCallbacks = new List <Action>())).Add(() => { // Finally, prep the parameter and attach the callback to it var targetMemberType = lastMemberAccess?.Type; int sizeToSet = (!size.HasValue && targetMemberType == typeof(string)) ? DbString.DefaultLength : size ?? 0; if (parameters.TryGetValue(dynamicParamName, out ParamInfo parameter)) { parameter.ParameterDirection = parameter.AttachedParam.Direction = ParameterDirection.InputOutput; if (parameter.AttachedParam.Size == 0) { parameter.Size = parameter.AttachedParam.Size = sizeToSet; } } else { dbType = (!dbType.HasValue) #pragma warning disable 618 ? SqlMapper.LookupDbType(targetMemberType, targetMemberType?.Name, true, out SqlMapper.ITypeHandler handler) #pragma warning restore 618 : dbType; // CameFromTemplate property would not apply here because this new param // Still needs to be added to the command Add(dynamicParamName, expression.Compile().Invoke(target), null, ParameterDirection.InputOutput, sizeToSet); } parameter = parameters[dynamicParamName]; parameter.OutputCallback = setter; parameter.OutputTarget = target; }); return(this); }
public static object QueryFirstOrDefault(this IDbConnection cnn, Type type, string sql, object param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null) { TRACE(sql); return(SqlMapper.QueryFirstOrDefault(cnn, type, sql, param, transaction, commandTimeout, commandType)); }
/// <summary> /// Creates a new <see cref="CountsRecord"/> by reading from the given multi-mapped reader. /// </summary> /// <param name="multi">The multi-mapped reader to read from.</param> /// <returns>A new <see cref="CountsRecord"/>.</returns> private static CountsRecord CreateCounts(SqlMapper.GridReader multi) { return new CountsRecord() { HistoryCount = multi.Read<long>().FirstOrDefault(), QueueCount = multi.Read<long>().FirstOrDefault(), ScheduleCount = multi.Read<long>().FirstOrDefault(), WorkerCount = multi.Read<long>().FirstOrDefault(), WorkingCount = multi.Read<long>().FirstOrDefault() }; }
public void AddParameters(IDbCommand command, SqlMapper.Identity identity) { var sqlCommand = (SqlCommand)command; sqlCommand.CommandType = CommandType.StoredProcedure; var groups = new List<SqlDataRecord>(); var rules = new List<SqlDataRecord>(); SqlMetaData[] groupSqlType = { new SqlMetaData("RuleGroupID", SqlDbType.Int), new SqlMetaData("GroupGuid", SqlDbType.VarChar, 32), new SqlMetaData("IsSystem", SqlDbType.Bit), new SqlMetaData("DisplayOrder", SqlDbType.Int), new SqlMetaData("[Enabled]", SqlDbType.Bit) }; SqlMetaData[] ruleSqlType = { new SqlMetaData("RuleDetailID", SqlDbType.Int), new SqlMetaData("RuleTypeID", SqlDbType.Int), new SqlMetaData("GroupGuid", SqlDbType.Char, 32), new SqlMetaData("RuleConfiguration", SqlDbType.Xml), new SqlMetaData("[Enabled]", SqlDbType.Bit) }; foreach (RuleGroup group in this._groups) { var groupRecord = new SqlDataRecord(groupSqlType); string groupGuid = Guid.NewGuid().ToString().Replace("-", string.Empty); groupRecord.SetInt32(0, group.ID); groupRecord.SetString(1, groupGuid); groupRecord.SetBoolean(2, group.IsSystem); groupRecord.SetInt32(3, group.DisplayOrder); groupRecord.SetBoolean(4, group.IsEnabled); groups.Add(groupRecord); foreach (var rule in group.Rules) { var ruleRecord = new SqlDataRecord(ruleSqlType); var ruleType = (int)rule.RuleTypeID; ruleRecord.SetInt32(0, rule.ID); ruleRecord.SetInt32(1, ruleType); ruleRecord.SetString(2, groupGuid); ruleRecord.SetString(3, this.RuleWriter(rule)); ruleRecord.SetSqlBoolean(4, rule.IsEnabled); rules.Add(ruleRecord); } } var userIDParam = sqlCommand.Parameters.Add("UserID", SqlDbType.Int); userIDParam.Value = this._userID; var profileIDParam = sqlCommand.Parameters.Add("ProFileID", SqlDbType.Int); profileIDParam.Value = this._profileID; var profileNameParam = sqlCommand.Parameters.Add("ProfileName", SqlDbType.VarChar, 50); profileNameParam.Value = this._profileName; var groupsPAram = sqlCommand.Parameters.Add("Groups", SqlDbType.Structured); groupsPAram.TypeName = "RulesGroupTableType"; groupsPAram.Value = groups; var rulesParam = sqlCommand.Parameters.Add("Rules", SqlDbType.Structured); rulesParam.TypeName = "RulesTableType"; rulesParam.Value = rules; }
public static Task <T> QuerySingleOrDefaultAsync <T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null) { TRACE(sql); return(SqlMapper.QuerySingleOrDefaultAsync <T>(cnn, sql, param, transaction, commandTimeout, commandType)); }