Thursday 19 January 2017

Create a mapping between the two different models using Automapper

In this post we are going to see how to create a mapping between the two different models using automapper and copy the data from one model to another model.

First we have to install the automapper using Nuget.






Create models

 public class PostViewModel
    {
        public HttpPostedFileBase File { setget; }

        public string PostTitle { setget; }

        public string PostDescription { setget; }
    }

    public class PostModel
    {
        public string Title { setget; }

        public string Description { setget; }

        public string Details
        {
            get { return string.Format("{0},{1}", Title,
                    Description.Substring(10) + "..."); }
        }

        public string imageUrl { setget; }

    }


Create a Profile for the mappings

public class PostToViewModelMappingProfile:Profile
    {
        public override string ProfileName
        {
            get
            {
                return "PostToViewModelMapping";
            }
        }

        protected override void Configure()
        {
            this.CreateMap<PostViewModelPostModel>()
                .ForMember(p => p.Title, pvm => pvm.MapFrom(vm => vm.PostTitle))
                .ForMember(p => p.Description, pvm => pvm.MapFrom(vm => vm.PostDescription));
        }

    }



then create a configuration class


    public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            AutoMapper.Mapper.Initialize(cf => {
                cf.AddProfile<PostToViewModelMappingProfile>();
            });
        }
    }


Invoke the configuration class in startup.cs


    public partial class Startup
    {       
        public void ConfigureAuth(IAppBuilder app)
        {
              AutoMapperConfiguration.Configure();

        }

    }


use the configuration to copy the value from one model to another

        public ActionResult Upload(PostViewModel model)
        {            
            var postmodel = Mapper.Map<PostViewModelPostModel>(model);
            postmodel.imageUrl = filename;
            return View(postmodel);
        }





From this post you can learn how to create a model mappings using automapper

No comments:

Post a Comment