1

I am trying to use AutoMapper 6.3 to allow me to auto map my models into view-models.

First I registered my AutoMapper instance to my IUnitContainer like so

var mapper = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<TaskViewModel, Task>();
});

container.RegisterInstance<IMapper>(mapper.CreateMapper()); 
container.RegisterType<IUserPassport, UserPassport>(); // This has nothing to do with AutoMapper but is needed to convert date time.

Now, in my controller, I want to pull a model from the database, then I want to map/cast it to my view-model.

I tried to do the following

var task = UnitOfWork.Tasks.Find(x => x.Id == 123)
                           .ProjectTo<TaskViewModel>()
                           .FirstOrDefault();

However, my view model need's to know current user's time zone in order to convert time from UTC to local time zone. Somehow, I need to be able to pass Passport.User.TimeZone to the ViewModel to be able to process datetime converson?

Here is how I am trying to project the viewModel

public class TaskController : Controller
{
    private IUserPassport Passport;
    public TaskController(IUserPassport passport)
    {
        Passport = passport;
    }

    public ActionResult Show(int? id)
    {
        if (!id.HasValue)
        {
            return HttpNotFound();
        }

        // Some how Passport.User.TimeZone needs to be passed to the 
        // TaskViewModel to the time stamps are converted.
        var task = UnitOfWork.Tasks.Find(x => x.Id == id.Value)
                               .ProjectTo<TaskViewModel>()
                               .FirstOrDefault();

        return View(task);
    }

}
Junior
  • 11,602
  • 27
  • 106
  • 212
  • You could write a custom resolver to do this. See [custom resolver documentation](https://github.com/AutoMapper/AutoMapper/blob/master/docs/Custom-value-resolvers.md) – penleychan Mar 02 '18 at 20:37
  • @12seconds how would I pass the User.TimeZone info to the resolver? – Junior Mar 02 '18 at 22:27
  • Resolvers don't work with ProjectTo. See [this](http://automapperdocs.readthedocs.io/en/latest/Queryable-Extensions.html#parameterization). – Lucian Bargaoanu Mar 03 '18 at 06:34
  • Do you want to add a property of type Timezone (may be not mapped to database) in your model and set it with Passport.User.TimeZone, and add the same to your ViewModel too ? Automapper will map it. – Milan Raval Mar 05 '18 at 20:37

0 Answers0