Wednesday, 20 April 2016

Dapper with MVC Application C# ASP.NET Example

Hi Guys, Hope you are enjoying coding...!!!! :) 

As i mentioned in my last post, i will come back with one of ORM.  so today i will try to explore about the new and second very fast ORM i.e. Dapper. 

Dapper is an open source, lightweight micro-ORM that simplifies data access while ensuring that your application is high-performant.

The following are the key features of Dapper:

  1. Speed and fast in performance.
  2. Operating directly to IDBConnection class that provides smoothness and running query directly to the database instead of passing data using various objects as we do in EF and ADO.NET.
  3. Static Object Binding.
  4. Dynamic Object Binding.
  5. Object Mapper.
  6. Multiple Query Support.
  7. Support for Stored Procedure.
  8. Bulk Data insert functionality.
  9. Dapper also allows fetching multiple data based on multiple inputs.
  10. Dapper allow to store bulk data at once.

Okay, lets have quick working example of DAPPER:

1. Create a Simple MVC website. 

2. Now install the Dapper from Nuget into your website. you can use "Install-Package Dapper" with package manager to install the Dapper.

Create a new Interface as below:

public interface IUserRepository
        List<User> GetAll();
        User Find(int id);
        User Add(User user);
        User Update(User user);
        void Remove(int id);
        User GetUserInformatiom(int id);

Now create new service Class or you can repository class as below:

  public class UserRepository : IUserRepository
        private IDbConnection _db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        public List<User> GetAll()
            return this._db.Query<User>("SELECT * FROM UserDetails").ToList();
            //return null;

I have created the example to get the users only, you can do as you want.

Now you can call this repository method in controller:

 public ActionResult Index()
            var model = _repository.GetAll();
            return View();

Summary : 

Dapper.NET is extremely easy to use and offers a high degree of flexibility with regard to how data is accessed and mapped to any business object. It also has the advantage of not requiring a cumbersome XML (or similar) definition file to set it up.

Happy Coding..