Obsivus
Obsivus

Reputation: 8359

MVC-ViewModel + Automapper: How would use of Automapper look on my code if I would like to use it?

I am using MVC-Viewmodel and EF model first for my projekt

These are my Viewmodels i'm using for my index view:

public class IndexViewModel
{
    public List<QuestionViewModel> Questionlist { get; set; }
}

&

   public class QuestionViewModel
    {
       public string QuestionText { get; set; }
       public List<string> CoreValues { get; set; }
       public List<string> SubjectTypes { get; set; }
       public int QID { get; set; }

   }
}

This is my Controller action:

public ActionResult Index()
    {
       List<Question> ListQuestions = Arep.getallquestion();
       var model = new IndexViewModel();
       model.Questionlist = new List<QuestionViewModel>();
       foreach (var item in ListQuestions)
       {
           var QuestionViewModel = new QuestionViewModel();
           model.Questionlist.Add(QuestionViewModel);
           QuestionViewModel.QuestionText = item.QuestionText;
           QuestionViewModel.QID = item.QID;
           QuestionViewModel.CoreValues = new List<string>();
           foreach (var Corevalue in item.CoreValue)
           {
               QuestionViewModel.CoreValues.Add(Corevalue.Cname);   
           }
           QuestionViewModel.SubjectTypes = new List<string>();
           foreach (var SubjectType in item.SubjectType)
           {
               QuestionViewModel.SubjectTypes.Add(SubjectType.Sname);
           }
       }

        return View(model);
    }

What my view UI does is displays lists with Questions.QuestionText that are related to a CoreValue.Cname and SubjectType.Sname. Question can have many CoreValues and SubjectType.

I would like to know how this code would look with use of Automapper, I would appreciate it alot!

Thanks in Advance!

Best regards!

Upvotes: 0

Views: 869

Answers (1)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

Untested, but :

First, You have the CreateMap part (usually somehwere in global.asax.cs)

Mapper.CreateMap<Question, QuestionViewModel>()
.ForMember(m => m.CoreValues, opt => opt.MapFrom(s => s.CoreValue.Select(x => x.Cname)))
.ForMember(m => m.SubjectTypes, opt => opt.MapFrom(s => s.SubjectType.Select(x => x.Sname)))

Then in your controller,

var model = new IndexViewModel();
model.Questionlist = Mapper.Map(Arep.getallquestions(), new List<QuestionViewModel>());
return View(model);

By the way, the code of your controller (without automapper) could be much more concise with a simple linq query !

Upvotes: 2

Related Questions