Dapper is an ORM (Object Relational Mapper) of .Net Framework. ORM is a programming technique which converts data between incompatible type system in object oriented programming language. ORM creates a virtual object database that can be used within your program. Microsoft provides a product of ORM framework which is Dapper Framework.

Create Database:
CREATE TABLE [dbo].[Contacts](
          [Id] [int] IDENTITY(1,1) NOT NULL,
          [FirstName] [varchar](50) NULL,
          [Lastname] [varchar](50) NULL,
          [Email] [varchar](50) NULL,
          [Company] [varchar](50) NULL,
          [Title] [varchar](50) NULL,
 CONSTRAINT [PK_Contacts] PRIMARY KEY CLUSTERED


After creating database, we create a new console application in Visual Studio


DapperExample.



Add an Application Configuration File in your project.

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
  </configSections>
  <connectionStrings>
    <add connectionString="Server=MINDSTICKSERVER\MSSQLSERVER2014;Database=ContactDB;User Id=UserName; Password=Password;" name="DefaultConnectionString" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>


Add a Class Contacts


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace DapperExample
{
    class Contacts
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Company { get; set; }
        public string Title { get; set; }
    }
}


Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
 
namespace DapperExample
{
    class Program
    {
       
 
        static void Main(string[] args)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;
            Contacts x = new Contacts();
            SqlConnection db = new SqlConnection(connectionString);
            string SqlString = "SELECT [FirstName],[LastName],[Email],[Company],[Title]FROM [Contacts]";
            var ourContacts = (List<Contacts>)db.Query<Contacts>(SqlString);
            foreach (var rec in ourContacts)
            {
                Console.WriteLine(new string('*', 20));
                Console.WriteLine("First Name: " + rec.FirstName);
                Console.WriteLine("Last Name: " + rec.LastName);
                Console.WriteLine("Email " + rec.Email );
                Console.WriteLine("Company "+rec.Company);
                Console.WriteLine("Title " + rec.Title);
                Console.WriteLine(new string('*', 20));
            }
            Console.Read();
        }
    }
}

  Modified On Nov-29-2017 02:18:13 PM

Leave Comment