English | Português (Brasil)
Este guia mostra padrões básicos de Dapper com o provider SQL Server,
Dapper.TypedParameters.SqlServer 1.0.0. Para PostgreSQL, veja o
guia do provider PostgreSQL.
- Um projeto com
net8.0ounet10.0. - Dapper.
Microsoft.Data.SqlClient.- Um banco SQL Server.
Instale o pacote stable atual pelo NuGet.org:
dotnet add package TypedParameters.Dapper.SqlServerPara uma instalação reproduzível da versão 1.0.0:
dotnet add package TypedParameters.Dapper.SqlServer --version 1.0.0Use o namespace do pacote no C#:
using Dapper.TypedParameters.SqlServer;using Dapper;
using Dapper.TypedParameters.SqlServer;
using Microsoft.Data.SqlClient;await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();var customer = await connection.QuerySingleOrDefaultAsync<Customer>(
"""
SELECT Id, Document, Name
FROM dbo.Customers
WHERE Document = @Document;
""",
new
{
Document = SqlParam.VarChar("12345678901", 11)
});int rows = await connection.ExecuteAsync(
"""
INSERT INTO dbo.Customers (Document, Name)
VALUES (@Document, @Name);
""",
new
{
Document = SqlParam.VarChar("12345678901", 11),
Name = SqlParam.NVarChar("Ada Lovelace", 100)
});int rows = await connection.ExecuteAsync(
"""
UPDATE dbo.Customers
SET Name = @Name
WHERE Document = @Document;
""",
new
{
Document = SqlParam.VarChar("12345678901", 11),
Name = SqlParam.NVarChar("Grace Hopper", 100)
});int rows = await connection.ExecuteAsync(
"DELETE FROM dbo.Customers WHERE Document = @Document;",
new
{
Document = SqlParam.VarChar("12345678901", 11)
});await connection.ExecuteAsync(
"""
UPDATE dbo.Customers
SET Nickname = @Nickname
WHERE Document = @Document;
""",
new
{
Document = SqlParam.VarChar("12345678901", 11),
Nickname = SqlParam.NVarChar(null, 80)
});null é convertido para DBNull.Value quando o parâmetro é materializado para
Microsoft.Data.SqlClient.
var invoice = await connection.QuerySingleAsync<Invoice>(
"""
SELECT Id, CustomerId, Amount
FROM dbo.Invoices
WHERE CustomerId = @CustomerId
AND Amount >= @MinimumAmount;
""",
new
{
CustomerId = SqlParam.Int(42),
MinimumAmount = SqlParam.Decimal(100M, precision: 18, scale: 2)
});