Skip to content

Instantly share code, notes, and snippets.

@bgrainger
Last active August 14, 2017 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgrainger/5f769e06bac7df8b15072e53145b6600 to your computer and use it in GitHub Desktop.
Save bgrainger/5f769e06bac7df8b15072e53145b6600 to your computer and use it in GitHub Desktop.
Formattable SQL
void Main()
{
var name = "test";
var state = "WA";
var cmd = new MySqlConnection().CreateCommand($"SELECT * FROM Customers WHERE Name = {name} AND State = {state};");
// cmd.CommandText == "SELECT * FROM Customers WHERE Name = @p0 AND State = @p1;"
}
public static class DbExtensions
{
public static DbCommand CreateCommand(this DbConnection connection, FormattableString sql)
{
var command = connection.CreateCommand();
command.CommandText = sql.ToString(new SqlFormatProvider(command));
return command;
}
}
public class SqlFormatProvider : IFormatProvider
{
public SqlFormatProvider(DbCommand command) => Formatter = new SqlFormatter(command);
public object GetFormat(Type formatType) => formatType == typeof(ICustomFormatter) ? Formatter : null;
private SqlFormatter Formatter { get;}
private class SqlFormatter : ICustomFormatter
{
public SqlFormatter(DbCommand command) => Command = command;
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (format != null)
throw new NotSupportedException($"Custom format '{format}' is not supported.");
var parameter = Command.CreateParameter();
parameter.ParameterName = "@p" + command.Parameters.Count.ToString();
parameter.Value = arg;
Command.Parameters.Add(parameter);
return parameter.ParameterName;
}
DbCommand Command { get; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment