articles

Home / DeveloperSection / Articles / Crud Operation Using Dapper Framework in C# Console Application

Crud Operation Using Dapper Framework in C# Console Application

Sushant Mishra16618 08-Mar-2017

Dapper is a micro-orm framework which is created by stack overflow for .net applications. ORM is provides you a technique to do operation with data in object format. You don’t need to worry about what type of data going to database.

In this article, we are going to do complete crud operation with user inputs using Dapper ORM framework in Console Application.

Create a database in Sql Server:
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
(
          [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]


1.   Create a Console Application in Visual Studio DapperExample and add references “Manage NuGet Packages”-> Dapper Install.

 Add following connectionString in App.config
<?xmlversion="1.0"encoding="utf-8" ?>
<configuration>
  <configSections>
  </configSections>
  <connectionStrings>
    <addconnectionString="Server=SERVER\MSSQLSERVER2014;Database=ContactDB;User Id=userName; Password=password;"name="DefaultConnectionString"providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

Add a POCO (Plain old CLR Object) Contacts


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace DapperExampleInsert
{
    publicclassContacts
    {
        publicint Id { get; set; }
        publicstring FirstName { get; set; }
        publicstring LastName { get; set; }
        publicstring Company { get; set; }
        publicstring Title { get; set; }
    }
}


Add an Interface IContactsRepository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace DapperExampleInsert
{
    interfaceIContactsRepository
    {
        List<Contacts> GetAll();
        bool Add(Contacts contacts);
        Contacts GetById(int id);
        bool Update(Contacts contacts,String ColumnWidth);
        bool Delete(int id);
    }
}


Add a Class which extend IContactsRepository and implement ContactsRepository


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace DapperExampleInsert
{
    class ContactsRepository :IContactsRepository
    {
        private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString);
       
        //Get Contacts Record By Id
        public Contacts GetById(int id)
        {
            return this.db.Query<Contacts>("Select * From Contacts Where Id=@Id", new { Id = id}).FirstOrDefault();
        }
        
        //Retreive the data from the table.
        public List<Contacts> GetAll()
        {
            return this.db.Query<Contacts>("Select * From Contacts").ToList();
        }
        //Add Employee Data
        public bool Add(Contacts contacts)
        {
            try
            {
                string sql = "INSERT INTO Contacts(FirstName,LastName,Company,Title) values(@FirstName,@LastName,@Company,@Title); SELECT CAST(SCOPE_IDENTITY() as int)";
                var returnId = this.db.Query<int>(sql, contacts).SingleOrDefault();
                contacts.Id = returnId;
            }
            catch (Exception ex)
            {
               
                return false;
            }
            return true;
        }
        //Update The Contacts Record
        public bool Update(Contacts contacts,String ColumnName)
        {
            string query = "update Contacts set " + ColumnName + "=@" + ColumnName + " Where Id=@Id";
            var count = this.db.Execute(query,contacts);
            return count > 0;
        }
        public bool Delete(int id)
        {
            var affectedrows = this.db.Execute("Delete from Contacts where Id=@Id", new {Id=id });
            return affectedrows > 0;
        }
    }
}



Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
namespace DapperExampleInsert
{
    class Program
    {
        public static IContactsRepository contactsRepository = new ContactsRepository();
        public void InsertData()
        {
            Console.WriteLine(new string('*', 20));
            Console.WriteLine("Enter the FirstName, LastName , Company And Title Of Contacts");
            Console.Write("First Name : ");
            String fName = Console.ReadLine();
            Console.Write("Last Name : ");
            String lName = Console.ReadLine();
            Console.Write("Company Name : ");
            String company = Console.ReadLine();
            Console.Write("Title Name : ");
            String title = Console.ReadLine();
            //inserting
            Contacts contacts1 = new Contacts 
            {
                FirstName = fName,
                LastName = lName,
                Company = company,
                Title = title
            };
            contactsRepository.Add(contacts1);
            ShowData();
            
        }
        public void ShowData()
        {
            Console.WriteLine(new string('*', 20));
            List<Contacts> contacts = contactsRepository.GetAll();
            foreach (var cont in contacts)
            {
                Console.WriteLine(cont.Id+" " + cont.FirstName + " " + cont.LastName + " " + cont.Company + " " + cont.Title);
            }
        }
        public void UpdatingData()
        {
            Console.WriteLine(new string('*', 20));
            //Updating
            Console.WriteLine("What Id do you want to Update ");
            int id = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("What do you want to Update....");
            Console.Write("First Name press 1 ");
            Console.Write(" Last Name press 2 ");
            Console.Write(" Company press 3 ");
            Console.Write(" Title press 4 ");
            int ch = Convert.ToInt32(Console.ReadLine());
            Contacts contacts = contactsRepository.GetById(id);
            String Name = null;
            switch (ch)
            {
                case 1:
                    Console.WriteLine("First Name : ");
                    string fName = Console.ReadLine();
                    contacts.FirstName = fName;
                    Name = "FirstName";
                    contactsRepository.Update(contacts, Name);
                    GetByID(id);
                    break;
                case 2:
                    Console.WriteLine("Lase Name : ");
                    string lName = Console.ReadLine();
                    contacts.LastName = lName;
                    Name = "LastName";
                    contactsRepository.Update(contacts, Name);
                    GetByID(id);
                    break;
                case 3:
                    Console.WriteLine("Company : ");
                    string company = Console.ReadLine();
                    contacts.Company = company;
                    Name = "Company";
                    contactsRepository.Update(contacts, Name);
                    GetByID(id);
                    break;
                case 4:
                    Console.WriteLine("Title : ");
                    string title = Console.ReadLine();
                    contacts.Title = title;
                    Name = "Title";
                    contactsRepository.Update(contacts, Name);
                    GetByID(id);
                    break;
                default:
                    Console.WriteLine("Please select a choice atleast");
                    break;
            }            
        }
        //Get By ID Method
        public void GetByID(int id)
        {
            Console.WriteLine(new string('*', 20));
            Contacts contacts2 = contactsRepository.GetById(id);
            if (contacts2 != null)
            {
                Console.WriteLine(contacts2.Id + " " + contacts2.FirstName + " " + contacts2.LastName + " " + contacts2.Company + " " + contacts2.Title);
            }
        }
        //Delete Method
        public void DeleteData()
        {
            Console.WriteLine(new string('*', 20));
            ShowData();
            Console.WriteLine(new string('*', 20));
            
            //Deletion
            Console.Write("What id do you want to delete :");
            int id = Convert.ToInt32(Console.ReadLine());
            contactsRepository.Delete(id);
            Contacts con = contactsRepository.GetById(3);
            if(con==null)
            {
                Console.WriteLine("Employee record is deleted already");
            }
            Console.WriteLine(new string('*', 20));
            ShowData();
        }
        public void SelectOption()
        {
            Console.WriteLine(new string('*', 20));
           
            Console.WriteLine("Welcome To Dapper Example :");
            Console.WriteLine(new string('*', 20));
            Console.WriteLine("For...");
            Console.WriteLine("Show Data Select 1");
            Console.WriteLine("Insert Data Select 2");
            Console.WriteLine("Update Data Select 3");
            Console.WriteLine("Delete Data Select 4");
            Console.WriteLine();
            Console.Write("Your Selection :  ");
            int selection = Convert.ToInt32(Console.ReadLine());
            switch (selection)
            {
                case 1:
                    ShowData();
                    break;
                case 2:
                    InsertData();
                    break;
                case 3:
                    UpdatingData();
                    break;
                case 4:
                    DeleteData();
                    break;
                default:                    
                    break;
            }
           
            Console.WriteLine(new string('*', 20));
        }
            
        static void Main(string[] args)
        {
            Program p = new Program();
            p.SelectOption();
            
           
            Console.ReadLine();
        }
    }
}

You can also visit this useful post


Updated 15-Jun-2020

Leave Comment

Comments

Liked By