Skip to content

Instantly share code, notes, and snippets.

@giacomelli
Created August 14, 2019 14:12
Show Gist options
  • Select an option

  • Save giacomelli/57f1f930ddd894eb8ab54fffed453842 to your computer and use it in GitHub Desktop.

Select an option

Save giacomelli/57f1f930ddd894eb8ab54fffed453842 to your computer and use it in GitHub Desktop.
conn.Execute(
"UPDATE Contact SET Date = @date, Info = @info WHERE ExternalId = @externalId",
new
{
Date = DateTime.UtcNow,
info = new DbString { Value = info, Length = 500, IsAnsi = false, IsFixedLength = false },
externalId = new DbString { Value = externalId, Length = 100, IsAnsi = true, IsFixedLength = false }
});
conn.Execute(
"UPDATE Contact SET Date = @date, Info = @info WHERE ExternalId = @externalId",
new
{
Date = DateTime.UtcNow,
info = info.ToNVarChar(500),
externalId = externalId.ToVarChar(100)
});
using Dapper;
/// <summary>
/// Extension methods for Dapper arguments
/// </summary>
/// <remarks>
/// The methods below are used to indicate the argument data type to Dapper and avoid the NVARCHAR(4000) arguments on SQL.
/// http://diegogiacomelli.com.br/dapper-and-the-nvarchar-4000-arguments
/// </remarks>
public static class DapperArgumentExtensions
{
/// <summary>
/// Builds a DbString argument as a VARCHAR.
/// </summary>
/// <param name="value">The argument value.</param>
/// <param name="length">The argument length.</param>
/// <returns>The configured DbString.</returns>
public static DbString ToVarChar(this string value, int length)
{
return new DbString
{
Value = value,
Length = length,
IsAnsi = true,
IsFixedLength = false
};
}
/// <summary>
/// Builds a DbString argument as a NVARCHAR.
/// </summary>
/// <param name="value">The argument value.</param>
/// <param name="length">The argument length.</param>
/// <returns>The configured DbString.</returns>
public static DbString ToNVarChar(this string value, int length)
{
return new DbString
{
Value = value,
Length = length,
IsAnsi = false,
IsFixedLength = false
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment