Asp.net

如何使用 AutoMapper 將多個對象映射到一個對象 - asp.net mvc 3

  • February 14, 2020

大家好/對 Auto-Mapper 非常陌生。我可以將一對一對象映射,但想知道是否可以將多個對象映射到一個對像或將多個對象映射到多個對象?

考慮我有以下情況……

使用者模型

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

公司模式

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
       }

使用者公司視圖模型

我想在一個視圖中顯示使用者列表及其公司詳細資訊..

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

現在,是否可以在這種情況下進行映射,如果可以,我可以在一個視圖中顯示,並且在編輯該視圖時,我想再次將更新的欄位映射回各自的模型。

任何幫助將不勝感激…謝謝

在這種情況下,您是否真的使用多個(類型)對像作為源?從您定義的問題看來,您的來源是使用者列表 - 從“我想顯示使用者列表及其公司詳細資訊”來判斷。

如果是這種情況,雖然你不能隱含地做到這一點,但你可以使用 aTypeConverter來輕鬆地執行地圖:

Mapper.CreateMap<ICollection<User>, UserCompanyViewModel>()
     .ConvertUsing<UserCompanyViewModelConverter>();

然後將您的轉換器定義為:

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;
   }
}

然後,當您想要映射時,您只需獲取使用者集合someUsers併映射它:

UserCompanyViewModel model = Mapper.Map<ICollection<User>, UserCompanyViewModel>(someUsers);

如果您確實需要將多個源類型映射到單個目標類型,那麼這篇博文似乎包含一個可以幫助您的簡短 Helper 類。簡而言之,AutoMapper 並不完全支持這一點,因此您將發出幾個 Map 請求來填充您的 ViewModel。您將需要使用另一個TypeConverter來確保第二個呼叫不會替換第一個呼叫添加的公司。

引用自:https://stackoverflow.com/questions/7580392