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


当前回答

需要安装一个安装自动程序的包。

添加AutoMapper.Extensions.Microsoft.DependencyInjection包

之后AddAutoMapper将在服务中可用。

public void ConfigureServices(IServiceCollection services)
{
     services.AddAutoMapper(typeof(Startup));
}

创建从Employee类到EmployeeDTO的映射器。

using AutoMapper;

public class AutomapperProfile: Profile
{
    public AutomapperProfile()
    {
        //Source to destination.
        CreateMap<Employee,EmployeeDTO>();
    }
}

EmployeeController从Employee映射到EmployeeDTo

using System.Collections.Generic;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;

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

    public EmployeeController(IMapper mapper)
    {
        _mapper = mapper;
    }

    [HttpGet]
    public IEnumerable<EmployeeDTO> GetEmployees()
    {
        /* 
        Assume it to be a  service call/database call
        it returns a list of employee, and now we will map it to EmployeeDTO
        */
        var employees = Employee.SetupEmployee();
        var employeeDTO = _mapper.Map<IEnumerable<EmployeeDTO>>(employees);
        return employeeDTO;

    }
}

Employee.cs供参考

using System.Collections.Generic;

public class Employee
{
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public int Salary { get; set; }

    public static IEnumerable<Employee> SetupEmployee()
    {
        return new List<Employee>()
        {
            new Employee(){EmployeeId = 1, EmployeeName ="First", Salary=10000},
            new Employee(){EmployeeId = 2, EmployeeName ="Second", Salary=20000},
            new Employee(){EmployeeId = 3, EmployeeName ="Third", Salary=30000},
            new Employee(){EmployeeId = 4, EmployeeName ="Fourth", Salary=40000},
            new Employee(){EmployeeId = 5, EmployeeName ="Fifth", Salary=50000}
        };
    }

}

EmployeeDTO.cs供参考

public class EmployeeDTO
{
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
}

其他回答

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()

在最新版本的asp.net core中,你应该使用以下初始化:

services.AddAutoMapper(typeof(YourMappingProfileClass));

我想扩展@theutz的答案-即这一行:

// services.AddAutoMapper(typeof(Startup));  // <-- newer automapper version uses this signature.

AutoMapper.Extensions.Microsoft.DependencyInjection版本3.2.0中有一个错误(可能)。(我使用的是。net Core 2.0)

这个问题在这个GitHub问题中解决。如果你继承AutoMapper的Profile类存在于你的Startup类所在的程序集之外,如果你的AutoMapper注入是这样的,它们可能不会被注册:

services.AddAutoMapper();

除非您显式指定要搜索AutoMapper概要文件的程序集。

在你的初创公司中也可以这样做。ConfigureServices:

services.AddAutoMapper(<assembies> or <type_in_assemblies>);

其中"assemblies"和"type_in_assemblies"指向应用程序中指定Profile类的程序集。例句:

services.AddAutoMapper(typeof(ProfileInOtherAssembly), typeof(ProfileInYetAnotherAssembly));

我认为(我强调这个词)由于以下无参数重载的实现(来自GitHub的源代码):

public static IServiceCollection AddAutoMapper(this IServiceCollection services)
{
     return services.AddAutoMapper(null, AppDomain.CurrentDomain.GetAssemblies());
}

我们依赖于CLR已经包含AutoMapper配置文件的JITed程序集,这可能是真的,也可能不是真的,因为它们只在需要时被jit(更多细节在这个StackOverflow问题中)。

我使用的是AutoMapper 6.1.1和asp.net Core 1.1.2。

首先,定义由Automapper的Profile Class继承的Profile类。我创建了IProfile接口,该接口为空,目的只是为了查找该类型的类。

 public class UserProfile : Profile, IProfile
    {
        public UserProfile()
        {
            CreateMap<User, UserModel>();
            CreateMap<UserModel, User>();
        }
    }

现在创建一个单独的类,例如Mappings

 public class Mappings
    {
     public static void RegisterMappings()
     {            
       var all =
       Assembly
          .GetEntryAssembly()
          .GetReferencedAssemblies()
          .Select(Assembly.Load)
          .SelectMany(x => x.DefinedTypes)
          .Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));

            foreach (var ti in all)
            {
                var t = ti.AsType();
                if (t.Equals(typeof(IProfile)))
                {
                    Mapper.Initialize(cfg =>
                    {
                        cfg.AddProfiles(t); // Initialise each Profile classe
                    });
                }
            }         
        }

    }

现在在MVC核心web项目的Startup.cs文件中,在构造函数中,调用Mapping类,它将在应用程序时初始化所有映射 装载。

Mappings.RegisterMappings();

在我的Startup.cs (Core 2.2, Automapper 8.1.1)

services.AddAutoMapper(new Type[] { typeof(DAL.MapperProfile) });            

在我的数据访问项目中

namespace DAL
{
    public class MapperProfile : Profile
    {
        // place holder for AddAutoMapper (to bring in the DAL assembly)
    }
}

在模型定义中

namespace DAL.Models
{
    public class PositionProfile : Profile
    {
        public PositionProfile()
        {
            CreateMap<Position, PositionDto_v1>();
        }
    }

    public class Position
    {
        ...
    }