Dapper requires writing SQL code, why?

2

I'm looking at the following link using Dapper: Getting Started With PostgreSQL Using Dapper In .NET Core and my question is, when I do it through Java I do not need to write the SQL code as this example here:

//1. Insert  
using (var conn = OpenConnection(_connStr))  
{  
    var insertSQL = string.Format(@"INSERT INTO public.customer(firstname, lastname, email,createtime)                    
    VALUES('{0}', '{1}', '{2}','{3}');", "Catcher", "Wong", "[email protected]", DateTime.Now);  
    var res = conn.Execute(insertSQL);  
    Console.WriteLine(res > 0 ? "insert successfully!" : "insert failure");  
    PrintData();  
}

For this example, do I really need to do this? if you need the benefit of using it?

    
asked by anonymous 17.08.2018 / 22:06

2 answers

4

Because the Dapper was created in this way, technologies have their own characteristics, either to meet a demand that requires it to be so, either by the will of the person who created it or by disability.

Dapper aims to access the database to generate an object for consumption in your application and virtually nothing else. Comparing with other technology does not make sense because another probably has another purpose. For example Entity Framework lets you do it another way.

Note that the code used is very bad and unsafe. I would not follow this tutorial. There is a close to what can be called a much better officer. See Execute() . Elias I would not suggest any tutorial, I would try to understand how everything works and why things, so you can make more appropriate decisions.

As seen on the same site, you can use an extension that avoids writing SQL to INSERT (with advantages and disadvantages).

    
17.08.2018 / 22:29
2

Complementing Maniero's response, your code is dangerous because you are concatenating the values in the string and are subject to a SQL Injection.

Here's a simple insert example with Dapper

// Insert
using (var db = new SqlConnection(connstring))
{
    const string sql = @"INSERT INTO [Region] (Name) VALUES (@Name)";

    db.Execute(sql, new { Name = region.Name }, commandType: CommandType.Text);
}

It has an extension for VisualStudio that I created to make life easier on some projects:

link

But for the use of this extension you have to create your Models, if you want to know a little more about what Model is already starting:

link

    
18.08.2018 / 00:57