Skip to main content

Dapper On Steroids: SqlKata

Dapper is a lightweight, high-performance ORM for .NET. It is widely used because of its simplicity and speed. Dapper in its essence provides simple mapping to POCO and works with raw queries minimizing the overhead. On the other hand it lacks of flexibility in terms of query writing, because we need to write queries like static strings. One simple example is shown in the code snippet below.

using System;
using System.Data.SqlClient;
using Dapper;

class Program
{
    static void Main(string[] args)
    {
        using (var connection = new SqlConnection("connection_string"))
        {
            connection.Open();

            string sql = "SELECT * FROM Companies";
            var companies = connection.Query<Company>(sql);
        }
    }
}


With the lack of flexibility in query construction, we would be in temptation to go for Entity Framework or some other heavy weight ORM, but there is also a simple library (SqlKata) which provides a decent flexibility in query construction and also keeps a full control over the generated query and we don't need to trade of the execution speed. 

The library itself is mostly based on Builder Design Pattern that is used for constructing queries. In the code snipet below is a simple example how to use the library.

var connection = new SqlConnection("connection string example");
var compiler = new SqlServerCompiler();
var db = new QueryFactory(connection, compiler);
var query = db.Query("Companies")
    .Select("Id", "Name")
    .Where("IsActive", true)
    .OrderBy("Name")
    .Limit(10);


The library also supports all other SQL comamnds, so it is worth to check it if you want to keep your query generation lighweight, simple and in your full control, what we cannot say for Entity Framework. Of course, this cannot be a full alternative to Entity Framework, but it can replace it in most cases.

Comments

Popular posts from this blog

Design Patterns: Builder

This is also, like a Singleton , one of the creational design patterns. It provides the way of creating complex objects step by step by simple chaining and every particular step is independent of other steps. Let us dive into the real example of usage. For showing purpose we have created an example in C# which creates simple SQL queries using described pattern.  using System; using System.Text; namespace BuilderPatternExample { public interface ISqlQueryBuilder { ISqlQueryBuilder Select(string columns); ISqlQueryBuilder From(string table); ISqlQueryBuilder Where(string condition); ISqlQueryBuilder OrderBy(string columns); string Build(); } public class SelectQueryBuilder : ISqlQueryBuilder { private readonly StringBuilder _queryBuilder; public SelectQueryBuilder() { _queryBuilder = new StringBuilder(); } public ISqlQueryBuilder Select(string columns) { ...

Design Patterns: Strategy

The Strategy Pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern allows the algorithm to be selected at runtime, providing flexibility in designing software. It’s particularly useful when you have multiple ways of performing a task, and you want to choose the implementation dynamically without altering the client code. When To Use It? You Have Multiple Algorithms or Behaviors. Use it when you have a need for muplitple ways of performing a task, and you want to make these implementations interchangeable. Examples: Different sorting algorithms, payment methods, discount calculations... You Want to Eliminate Conditional Logic.  If you find yourself writing large if-else or switch statements to decide which algorithm to use, this pattern can simplify and clean up your code. Examples: A game character with different attack styles  You Need Runtime Flexibility.  Use this pattern if the ...

Design Patterns: Singleton

Tyipically the first design pattern most people learn, often wrongly ☺ To give an introduction, we can say that singleton is one of the creational design patterns which ensures only one class instance with single point of access thru entire application.  Because it is relatively simple to implement, the Singleton pattern is sometimes misapplied in situations where it is not the most suitable choice. When to use it? Here are the few examples of corrent usage of singleton: Configuration Management  Centralized configuration settings for consistent use thru entire application Caching Maintaning  Single istance of cached objects for easy and fast acces Logging  Ensure unified mechanism to avoid duplication of log files, formats, etc Global State Management  Centralized management of the state which is needed to be shared accross the application Resource sharing  Thread pools, database connection, I/O operations When not to use it? On the other hand, here are fe...