Dapper requires writing SQL code, why?

Asked

Viewed 271 times

2

I’m looking at the following link that uses Dapper: Getting Started With Postgresql Using Dapper In . NET Core and my question is, when I do Java I don’t need to write 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 I really need to do this? if I need the advantage of using it?

  • 1

    I don’t understand what Java has to do with it.

2 answers

4


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

Dapper aims to access the database and generate an object for consumption in your application and practically nothing else. Comparing with other technology makes no sense because another one probably has another goal. For example the Entity Framework allows you to do otherwise.

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

As can be seen on the same site it is possible to use a extension that avoids writing SQL to the INSERT (with both advantages and disadvantages).

3

Complementing Maniero’s answer, your code is dangerous because you are concatenating the values into the string and are subject to an SQL Injection.

Here’s a simple example of Insert 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);
}

There is an extension to Visualstudio that I created to make life easier in some projects:

https://marketplace.visualstudio.com/items?itemName=thiagoguaru.DapperCrudGenerator

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

https://docs.microsoft.com/pt-br/aspnet/mvc/overview/older-versions/getting-started-with-aspnet-mvc3/cs/adding-a-model

Browser other questions tagged

You are not signed in. Login or sign up in order to post.