how to map multiple OBJECTS to one object using AutoMapper - asp.net mvc 3
you can use modelMapper
@Autowired
private ModelMapper modelMapper;
and in function
Desination desination = modelMapper.map(obj1, Desination.class);
modelMapper.map(obj2, desination);
In this case, are you really using multiple (types of) objects as your source? It looks like from your defined problem that your source is a list of users - judging by "i want to show List of users with their company details".
If that's the case, whilst you can't do it implicitly you can use a TypeConverter
to perform the map easily enough:
Mapper.CreateMap<ICollection<User>, UserCompanyViewModel>()
.ConvertUsing<UserCompanyViewModelConverter>();
Then define your converter as:
public class UserCompanyViewModelConverter : ITypeConverter<ICollection<User>, UserCompanyViewModel>
{
public UserCompanyViewModel Convert(ResolutionContext context)
{
UserCompanyViewModel model = new UserCompanyViewModel();
ICollection<User> sourceUsers = (ICollection<User>)context.SourceValue;
model.Users = sourceUsers;
model.Companies = sourceUsers.Select(u => u.Company).Distinct().ToList();
return model;
}
}
Then when you want to map you just take your collection of users someUsers
and map it:
UserCompanyViewModel model = Mapper.Map<ICollection<User>, UserCompanyViewModel>(someUsers);
If you really do need to map multiple source types into a single destination type, it looks like this blog post includes a short Helper class that will help you. In short, AutoMapper doesn't quite support this so you will be making a couple of Map requests to fill up your ViewModel. You will need to use another TypeConverter
to make sure that the second call doesn't replace the Companies added by the first.