how to use automapper in webapi

 

AutoMapper:- AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper’s established convention, almost zero configuration is needed to map two types.


Step 1:- Create a web api project in visual studio 



Step 2:- Now create a table in Sql-Server and link this table to your application using DbFirst Approach.  


CREATE TABLE [dbo].[tblStudent](
       [Id] [int] IDENTITY(1,1) NOT NULL,
       [Name] [nvarchar](50) NULL,
       [DOB] [date] NULL,
       [Course] [nvarchar](50) NULL,
 CONSTRAINT [PK_tblStudent] 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]
 
GO

 




Step 3:- Create a folder Dto in your Soultion folder and add a class file with StudentModel
namespace AutoMapper_InWebApi.Dto
{
    public class StudentModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string DOB { get; set; }
        public string Course { get; set; }
    }
}


Step 4:- Now install AutoMapper in your project soulution from menu bar in visual studio

 Tools>Nuget Package Manager>Manage Nuget Packages for solutions ,you can check automapper compatible version according to to your visual studio in Version dropdown in right side  





Step5:- Add a folder in Solution Helpers and add a class file with name ApplicationMapping.cs 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using AutoMapper;

using AutoMapper_InWebApi.Dto;

using AutoMapper_InWebApi.Models;

 

namespace AutoMapper_InWebApi.Helpers

{

    public class ApplicationMapping:Profile

    {

        public ApplicationMapping()

        {

            CreateMap<tblStudent, StudentModel>().ReverseMap();

        }

    }

}



Step 6:- Now Add a Empty Controller with name Students in Your Controller folder and Paste the following code in this Controller.cs file   

StudentsController.cs

using AutoMapper_InWebApi.Dto;

using AutoMapper_InWebApi.Models;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Web.Http;

using AutoMapper;

 

namespace AutoMapper_InWebApi.Controllers

{

    public class StudentsController : ApiController

    {

        BlogDatabaseEntities _context = new BlogDatabaseEntities();

 

        public IEnumerable<StudentModel> GetStudents()

        {

            var students = _context.tblStudent.ToList().Select(Mapper.Map<tblStudent,StudentModel>);

            return students;

        }

 

        public StudentModel GetStudentById(int id)

        {

            var student = _context.tblStudent.SingleOrDefault(c => c.Id == id);

            if (student == null)

                throw new HttpResponseException(HttpStatusCode.BadRequest);

            return Mapper.Map<tblStudent,StudentModel>(student);

        }

 

       

        public StudentModel PostStudent(StudentModel model)

        {

            if (!ModelState.IsValid)

                throw new HttpResponseException(HttpStatusCode.BadRequest);

 

            var student = Mapper.Map<StudentModel, tblStudent>(model);

            _context.tblStudent.Add(student);

            _context.SaveChanges();

            model.Id = student.Id;

            return model;

        }

 

    }

}


Step7:- Now run your and check it in Postman or fiddler 

 



 

No comments:

Post a Comment