First, it is important to say that Dapper works very well as an addition to the Entity Framework. Using only Dapper in your application can result in a loss of productivity, since Dapper does not have, for example, lazy load, incremental bank control and dynamic SQL generation. Everything is the responsibility of the programmer, who has to write all the interface sentences with the bank manually.
For this answer, I’ll assume you’re considering using both. No problem not using, but the development will get more work and I hope to be able to show it here.
With this in mind, we can write a quick guide to Dapper.
Using with the Entity Framework
Dapper is basically a library that extends IDbConnection
. Starting a new project with Entity Framework, using Dapper is quite simple:
using Dapper;
private EntityFrameworkContext context = new EntityFrameworkContext();
...
db.Database.Connection.Query(); // Query já é um dos métodos do Dapper.
Selecting
I’ll use Pais
for example.
A Country
var umPais = context.Database.Connection.Query<Pais>("select * from Paises where PaisId = @Id", new { Id = 1 }).FirstOrDefault();
All countries
var todosOsPaises = context.Database.Connection.Paises.Query<List<Pais>>("select * from Paises");
Joins
I’ll use it now Estado
and Pais
:
var sql = @"select e.EstadoId, e.Nome, e.Sigla, e.PaisId, p.PaisId, p.Nome, p.Sigla
from Estados e
inner join Paises p on e.PaisId = p.PaisId";
var estadosEPaises = db.Database.Connection
.Query<Estado, Pais, Estado>(sql,
(e, p) => {
e.Pais = p;
return e;
},
splitOn: "PaisId");
Inserting
var resultadosAfetados = db.Database.Connection.Execute("insert into Paises (Nome, Sigla) values (@Nome, @Sigla)", new { Nome = "Brasil", Sigla = "BR" });
You can insert several:
var resultadosAfetados = db.Database.Connection.Execute("insert into Paises (Nome, Sigla) values (@Nome, @Sigla)", new[] { { Nome = "Brasil", Sigla = "BR" }, { Nome = "Portugal", Sigla = "PT" } });
Updating
Same thing:
var resultadosAfetados = db.Database.Connection.Execute("update Paises set Nome = @Nome where Sigla = @Sigla", new { Nome = "Brazil", Sigla = "BR" });
Excluding
I need to put?
Facilitating
Write methods of insertion, deletion, etc., can be well tedious, so the Dapper team created a method that makes it not necessary to write inserts and updates:
using Dapper.Contrib.Extensions;
public void Persistir(IDbConnection connection, Usuario usuario)
{
if (usuario.UsuarioId == null) {
SqlMapperExtensions.Insert(connection, usuario);
}
else {
SqlMapperExtensions.Update(connection, usuario);
}
}
I saw that there is a Dapper.Entityframework in the Dapper source. Why don’t you use?
Because it contains only two types to work properly with geographical and geometric coordinates. Has little use in the examples that are part of the question.
Add the schema of the tables and the relationships between them for easy analysis.
– user28595