1

I've been using Dapper like this to do queries (simplified psudeo-code):

var sql = "SELECT * FROM EMPLOYEE;"
using (Connection)
{
    return Connection.Query<Employee>(sql);
}

I was wondering if this is considered "inline SQL", which is bad according to a lot of people.

Barry Franklin
  • 1,781
  • 1
  • 27
  • 45
  • See https://stackoverflow.com/questions/13653461/dapper-and-sql-injections – DotNetDublin Mar 18 '21 at 23:38
  • I'd also consider utilising Dapper.Contrib https://dotnetcoretutorials.com/2019/08/05/dapper-in-net-core-part-4-dapper-contrib/ – DotNetDublin Mar 18 '21 at 23:40
  • The inline SQL that most people consider bad is when the SQL is generated dynamically. You should be able to pass a `const string sql` to `Query()`, no formatting/interpolation, no `+`, no `string.Join`. The above is not a problem. Other issues: don't use `select *`, specify the exact columns you need. Don't cache connection objects, create a new one every time from connection string – Charlieface Mar 19 '21 at 00:48

1 Answers1

2

Yes, that is inline SQL. However, inline SQL isn't "bad" in any way; the only truly "bad" thing is not using parameters, which is something Dapper makes trivial to get right. Most arguments against inline SQL are falsely equating the two concepts. There are discussions about the pros/cons of stored procedures vs inline SQL, but it is subjective and there very much are pros and cons of each. Plus Dapper can use stored procedures anyway.

It isn't exactly the same, but there's a lot of crossover with my thoughts here: https://blog.marcgravell.com/2017/12/dapper-prepared-statements-and-car-tyres.html

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900