在这种情况下,我无法关注wiki。我想使用Automapper 5.2。我找不到一个结束示例的简单结尾,它显示了具有上下文的可靠配置。根据上下文,我的意思是你在哪里放置配置文件,以及静态和实例api之间的区别?
我查看了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核心..没有Global.asax文件..
如果有的话,你在Startup.cs文件中放了什么?
鉴于以上这两个文件,我需要做什么才能使用Automapper?
此致
答案 0 :(得分:7)
以下是在asp.net core mvc中配置automapper的步骤。
1。创建从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;
}
}
3。创建扩展方法,我们可以将其添加到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. 在Startup.cs ConfigureServices
方法
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DBContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
services.AddAutoMapper();
}