0

I am trying to leverage the Automapper for mapping the controller methods to the viewmodel properties in an asp.net mvc project. I analyzed few articles about Automapper and found that it is wonderful object to object mapper between complex model object and viewmodel object. I have code in a controller: CustomersController.cs

[Authorize(Roles = "Administrator")]
        public ActionResult Index()
        {
            var user = _userService.GetUser(_profile.UserName);
            if (!user.IsActive)
                return RedirectToAction("");

            var clientGroups = new List<ClientGroup>();                 

            var model = new CustomerGroupsIndexViewModel()
            {

                CustomerGroupUsersUrl = Url.RouteUrl<CustomerGroupsController>(c => c.GetUsersForCustomerGroup(null, null, null, 0, 0)),
                CustomerGroupByAreaUrl = Url.RouteUrl<CustomerGroupsController >(c => c.GetAreaDetailsForCustomerGroup(null, null, null, 0, 0)),

                CheckLoginNameUrl = Url.RouteUrl<UsersController>(c => c.CheckLoginName(null)),
                ResetUserUrl = Url.RouteUrl<UsersController>(c => c.ResetPassword(null)),
                GetSelectOptionsForCustomerGroupUrl = Url.RouteUrl<ClientGroupsController>(c => c.GetSelectOptionsForCustomerGroup(null,null)),

                FindUsersMatchingTermUrl = Url.RouteUrl<UsersController>(c => c.FindUsersMatchingWithLoginName(null)),
                NumberOfTestTaken = _scanService.GetCustomerForUser(user).Count(),                
                RefreshCustomerGroupUrl = Url.RouteUrl<CustomerGroupsController >(c => c.RefreshClientGroup()),
            };

            Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();

            return View("CustomerGroupIndex", model);
        }

I have such methods across the project code base. Can anyone help me how can I use Automapper efficiently here?

Thanks & Regards, Santosh Kumar Patro

1 Answer 1

2

I 'll explain it very briefly

Create configuration for each Model and related ViewModel like this

Interface for configuration:

interface IGlobalConfiguration
    {
        void Configure();
    }

Class for configuration:

public class AutoMapperViewModelConfiguration : IGlobalConfiguration
    {
        public void Configure()
        {
            Mapper.CreateMap<Model1,ViewModel1>();

            Mapper.CreateMap<ViewModel1,Model1>()
        .ForMember(x => x.ModelMember1, y => y.Ignore());//Ignore if not required
        }
    }

Create a class and method like this:

public class GlobalConfigurationModule
    {
        private readonly Assembly assembly;

        public GlobalConfigurationModule()
            : this(Assembly.GetExecutingAssembly())
        {
        }

        public GlobalConfigurationModule(Assembly assembly)
        {
            this.assembly = assembly;
        }

        public void Load()
        {
            var ins = from x in assembly.GetExportedTypes()
                      where x.GetInterfaces().Contains(typeof(IGlobalConfiguration))
                      select Activator.CreateInstance(x) as IGlobalConfiguration;

            foreach (var config in ins)
            {
                config.Configure();
            }
        }
    }

Call the Load method in Global.asax

protected void Application_Start()
        {

            new GlobalConfigurationModule().Load();
}

When you require to map a Model to ViewModel use this Mapper.Map() method like this:

Mapper.Map(model1Object, viewModel1Object);

Edit:

If you need the mapping should be done from a method you can create mapping like this.

Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.SomeValue, 
        opt => opt.MapFrom(src => src.GetSomeValue()))

You cannot map a method returns void.

Cheers

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply Prasanth. Here you have created the mapping between Model and ViewModel. Can you please help me by showing a code sample showing the mapping between the controller methods and the viewmode?
Can you please give me a clear idea about your requirement? I have given you the sample code. It clearly shows how to map between different models. If you need to map using automapper you can add a configuration in the configuration file.
I have some methods within the controller class:CustomerController.cs which I need to map to the viewmodel properties. I have drafted the code sample in the question section above.Can you please help how I can use Automapper in this case?
If you need to map from a method you have to use mapping as above (please see edited section).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.