20 September 2018

Dapper ORM (A simple implementation) Part 1

I recommed the use of Dapper. Aside from it's developed by a good team from Stack Overflow, it was built with performance in mind. And on top of that, Dapper is lightweight and very fast compared to other ORMs.

You may install Dapper from the NuGet.

The implementation is so easy to do.

Here in my example, I'll show you how to get a list of users with the Query() extension method of Dapper to retrieve all the records from the User table in our UserDb database:



private readonly string connectionString = "Server=BDF_SERVER;Database=UserDb;Trusted_Connection=True;";


//To display all the users from the table
public List<User> Display_All_Users()
{
    using (var con = new SqlConnection(connectionString))
    {
        string strRead = "SELECT * FROM User";
        return con.Query<User>(strRead).ToList();
    }
}


//To search a particular user from the table

public User Display_User_By_Id(int id) 
{
    using (var con = new SqlConnection(connectionString))
    {
        string strRead = "Select * From User WHERE Id = @Id"
        return con.Query<User>(strRead, new { id }).SingleOrDefault();
    }
}

No comments:

Post a Comment