我是。net的新手,所以我决定使用。net Core,而不是学习“老方法”。我在这里找到了一篇关于为。net Core设置AutoMapper的详细文章,但是对于新手来说还有更简单的操作指南吗?


当前回答

关于这个问题的答案, 不需要在控制器构造函数中指定IMapper映射器参数。

您可以使用Mapper,因为它是代码任何位置的静态成员。

public class UserController : Controller {
   public someMethod()
   {
      Mapper.Map<User, UserDto>(user);
   }
}

其他回答

我想明白了!细节如下:

Add the main AutoMapper Package to your solution via NuGet. Add the AutoMapper Dependency Injection Package to your solution via NuGet. Create a new class for a mapping profile. (I made a class in the main solution directory called MappingProfile.cs and add the following code.) I'll use a User and UserDto object as an example. public class MappingProfile : Profile { public MappingProfile() { // Add as many of these lines as you need to map your objects CreateMap<User, UserDto>(); CreateMap<UserDto, User>(); } } Then add the AutoMapperConfiguration in the Startup.cs as shown below: public void ConfigureServices(IServiceCollection services) { // .... Ignore code before this // Auto Mapper Configurations var mapperConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); IMapper mapper = mapperConfig.CreateMapper(); services.AddSingleton(mapper); services.AddMvc(); } To invoke the mapped object in code, do something like the following: public class UserController : Controller { // Create a field to store the mapper object private readonly IMapper _mapper; // Assign the object in the constructor for dependency injection public UserController(IMapper mapper) { _mapper = mapper; } public async Task<IActionResult> Edit(string id) { // Instantiate source object // (Get it from the database or whatever your code calls for) var user = await _context.Users .SingleOrDefaultAsync(u => u.Id == id); // Instantiate the mapped data transfer object // using the mapper you stored in the private field. // The type of the source object is the first type argument // and the type of the destination is the second. // Pass the source object you just instantiated above // as the argument to the _mapper.Map<>() method. var model = _mapper.Map<UserDto>(user); // .... Do whatever you want after that! } }

services.AddAutoMapper ();对我没用。(我用的是Asp。Net Core 2.0)

配置如下

   var config = new AutoMapper.MapperConfiguration(cfg =>
   {                 
       cfg.CreateMap<ClientCustomer, Models.Customer>();
   });

初始化映射器 IMapper mapper = config.CreateMapper();

并将mapper对象作为单例添加到服务中 services.AddSingleton(映射);

这样我就可以添加DI到控制器

  private IMapper autoMapper = null;

  public VerifyController(IMapper mapper)
  {              
   autoMapper = mapper;  
  }

我在我的动作方法中使用了如下

  ClientCustomer customerObj = autoMapper.Map<ClientCustomer>(customer);

theutz的回答很好,我只想补充一点:

如果你让你的映射配置文件继承自MapperConfigurationExpression而不是profile,你可以非常简单地添加一个测试来验证你的映射设置,这总是很方便:

[Fact]
public void MappingProfile_VerifyMappings()
{
    var mappingProfile = new MappingProfile();

    var config = new MapperConfiguration(mappingProfile);
    var mapper = new Mapper(config);

    (mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
}

我用这种方式解决了它(类似于上面,但我觉得这是一个更干净的解决方案)。net Core 3.x

创建MappingProfile.cs类并使用Maps填充构造函数(我计划使用一个类来保存所有映射)

    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<Source, Dest>().ReverseMap();
        }
    }

在Startup.cs中,添加下面的内容以添加到DI(程序集参数用于保存映射配置的类,在我的例子中,它是MappingProfile类)。

//add automapper DI
services.AddAutoMapper(typeof(MappingProfile));

在Controller中,像使用其他DI对象一样使用它

    [Route("api/[controller]")]
    [ApiController]
    public class AnyController : ControllerBase
    {
        private readonly IMapper _mapper;

        public AnyController(IMapper mapper)
        {
            _mapper = mapper;
        }
        
        public IActionResult Get(int id)
        {
            var entity = repository.Get(id);
            var dto = _mapper.Map<Dest>(entity);
            
            return Ok(dto);
        }
    }


ASP。NET Core(使用2.0+和3.0测试),如果你喜欢阅读源文档: https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/README.md

否则,遵循以下4个步骤即可:

从nuget安装AutoMapper.Extensions.Microsoft.DependancyInjection。 只需添加一些概要文件类。 然后将以下内容添加到你的startup.cs类中。 services.AddAutoMapper (OneOfYourProfileClassNamesHere) 然后简单地在你的控制器或任何你需要它的地方注入IMapper:

public class EmployeesController {

    private readonly IMapper _mapper;

    public EmployeesController(IMapper mapper){

        _mapper = mapper;
    }

如果你想使用ProjectTo,现在很简单:

var customers = await dbContext.Customers.ProjectTo<CustomerDto>(_mapper.ConfigurationProvider).ToListAsync()