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


当前回答

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

其他回答

在我的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
    {
        ...
    }

使用ASP使用AutoMapper。净的核心。

步骤1。从NuGet包中安装AutoMapper.Extensions.Microsoft.DependencyInjection。

步骤2。在“解决方案”中创建一个文件夹以保存名称为“Mappings”的映射。

步骤3。添加映射文件夹后,我们添加了一个名为“MappingProfile”的类,这个名称可以是唯一的,很好理解。

在本课程中,我们将维护所有映射。

步骤4。在启动“ConfigureServices”时初始化映射器

在启动类,我们需要初始化配置文件,我们已经创建和注册AutoMapper服务。

  Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());

  services.AddAutoMapper();

显示ConfigureServices方法的代码片段,其中我们需要初始化和注册AutoMapper。

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }


    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });


        // Start Registering and Initializing AutoMapper

        Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
        services.AddAutoMapper();

        // End Registering and Initializing AutoMapper

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    }}

第5步。得到的输出。

为了获得映射结果,我们需要调用AutoMapper.Mapper.Map并传递正确的目的地和源。

AutoMapper.Mapper.Map<Destination>(source);

CodeSnippet

    [HttpPost]
    public void Post([FromBody] SchemeMasterViewModel schemeMaster)
    {
        if (ModelState.IsValid)
        {
            var mappedresult = AutoMapper.Mapper.Map<SchemeMaster>(schemeMaster);
        }
    }

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

我想明白了!细节如下:

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

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

services.AddAutoMapper(typeof(YourMappingProfileClass));