2016-12-19 34 views
0

在這種情況下,我無法關注wiki。我想使用Automapper 5.2。我無法找到結束示例的簡單結尾,它顯示了具有上下文的可靠配置。根據上下文,我的意思是你把配置文件放在哪裏以及靜態和實例api之間有什麼區別?設置Automapper 5.1

我檢出了DNRTV下載,但它處理1.0版本。

如何設置此包?我有一個名爲Client的模型,如下所示。

public class Client : IEntityBase 
{ 
    public Client() 
    { 
     Jobs = new List<Job>(); 
    } 
    public int Id { get; set; } 
    public int ClientNo { get; set; } 
    public bool Company { get; set; } 
    public string CompanyName { get; set; } 
    public string ClientFirstName { get; set; } 
    public DateTime DeActivated { get; set; } 
    public bool Activity { get; set; } 
    public DateTime DateCreated { get; set; } 
    public DateTime DateUpdated { get; set; } 

    public int? StateId { get; set; } 
    public State State { get; set; } 

    public int CreatorId { get; set; } 
    public User Creator { get; set; } 

    public ICollection<Job> Jobs { get; set; } 
} 

和ClientViewModel像這樣:

public class ClientViewModel 
{ 
    public int Id { get; set; } 
    public int ClientNo { get; set; } 
    public bool Company { get; set; } 
    public string CompanyName { get; set; } 
    public string ClientFirstName { get; set; } 
    public DateTime DeActivated { get; set; } 
    public bool Activity { get; set; } 
    public DateTime DateCreated { get; set; } 
    public DateTime DateUpdated { get; set; } 
    public int? StateId { get; set; } 
    public int CreatorId { get; set; } 
    public int[] Jobs { get; set; } 
} 

我不能確定如何設置AutoMapper了關於配置。也就是說,他們談論的是一個global.asax文件,而我正在使用aspnet core ..沒有Global.asax文件..

如果有什麼,你會在Startup.cs文件中放什麼。

鑑於上述這兩個文件,我需要做些什麼才能將Automapper與它們結合使用?

Regards

回答

7

這裏是在asp.net core mvc中配置automapper的步驟。

創建從Profile

public class ClientMappingProfile : Profile 
{ 
    public ClientMappingProfile() 
    { 
     CreateMap<Client, ClientViewModel>().ReverseMap(); 
    } 
} 

2.創建AutoMapper配置類,在這裏添加您的映射輪廓類擴展映射文件類。

public class AutoMapperConfiguration 
{ 
    public MapperConfiguration Configure() 
    { 
     var config = new MapperConfiguration(cfg => 
     { 
      cfg.AddProfile<ClientMappingProfile>(); 
     }); 
     return config; 
    } 
} 

創建擴展方法,這樣,我們就可以在Startup.cs ConfigureServices方法

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddDbContext<DBContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 
    services.AddMvc(); 

    services.AddAutoMapper(); 
} 
+0

一些具體的內容添加到Startup.cs ConfigureServices方法

public static class CustomMvcServiceCollectionExtensions { public static void AddAutoMapper(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } var config = new AutoMapperConfiguration().Configure(); services.AddSingleton<IMapper>(sp => config.CreateMapper()); } } 

4.調用擴展方法。 。非常感謝你..將投票這!!我有一個問題。「.ReverseMap()」做什麼? – si2030

+0

它做了雙向映射像上面的例子客戶端到ClientViewModel和ClientViewModel到客戶端 – Ahmar

+0

我已經投了這個。 – si2030