how to map multiple OBJECTS to one object using Au

2019-01-22 15:18发布

问题:

Hi All / very new to Auto-Mapper. i can map one to one objects but was wondering is it possible to map multiple objects to one object or multiple objects to multiple objects?

consider i have a following scenario...

User Model

public class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Company Company { get; set; }  // 1 user work in 1 company
    }

Company Model

public class Company
        {
            public string CompanyName { get; set; }
            public string Website { get; set; }
            public ICollection<User> Users { get; set; }  // 1 Company can have many users
        }

UserCompanyViewModel

i want to show List of users with their company details in one view..

public class UserCompanyViewModel
            {
                 public ICollection<User> Users { get; set; }
                 ppublic ICollection<Company> Companies { get; set; }   
            }

Now, is it possible to map in this situation and if yes, i can show in one view and when editing that view i want to map again with the updated fields back to their respective Models.

any help would be appreciated...thx

回答1:

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.