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


当前回答

我想明白了!细节如下:

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

其他回答

对于使用。net 7的AutoMapper 11.0.1,我开始得到这个异常:

System.ArgumentException: 'GenericArguments[0], 'System.DateTime', on 'T MaxInteger[T](System.Collections.Generic.IEnumerable`1[T])' violates the constraint of type 'T'.'

Inner Exception
VerificationException: Method System.Linq.Enumerable.MaxInteger: type argument 'System.DateTime' violates the constraint of type parameter 'T'.

看这个问题:

系统。DateTime on 'T MaxInteger[T](System.Collections.Generic.IEnumerable ' 1[T])'违反了。net 7使用AutoMapper 11.0.1的T类型约束

这意味着我不能再使用services.AddAutoMapper(typeof(MappingProfile).Assembly);无一例外。

对于AutoMapper.Extensions.Microsoft.DependencyInjection我这样解决它:

services.AddAutoMapper(cfg => cfg.Internal().MethodMappingEnabled = false, typeof(MappingProfile).Assembly);

对于Blazor WebAssembly客户端,解决方案是这样的:

var mapperConfig = new MapperConfiguration(mc =>
{
    //Needed for https://github.com/AutoMapper/AutoMapper/issues/3988
    mc.Internal().MethodMappingEnabled = false;
    mc.AddProfile(new MappingProfile());
});
//mapperConfig.AssertConfigurationIsValid();

IMapper mapper = mapperConfig.CreateMapper();
builder.Services.AddSingleton(mapper);

我喜欢很多答案,尤其是@saineshwar的答案。我使用的是。net Core 3.0和AutoMapper 9.0,所以我觉得是时候更新答案了。

对我有用的是在Startup.ConfigureServices(…)中以这样的方式注册服务:

    services.AddAutoMapper(cfg => cfg.AddProfile<MappingProfile>(), 
                               AppDomain.CurrentDomain.GetAssemblies());

我认为@saineshwar的其余答案保持完美。但如果有人感兴趣,我的控制器代码是:

[HttpGet("{id}")]
public async Task<ActionResult> GetIic(int id)
{
    // _context is a DB provider
    var Iic = await _context.Find(id).ConfigureAwait(false);

    if (Iic == null)
    {
        return NotFound();
    }

    var map = _mapper.Map<IicVM>(Iic);

    return Ok(map);
}

我的映射类:

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Iic, IicVM>()
            .ForMember(dest => dest.DepartmentName, o => o.MapFrom(src => src.Department.Name))
            .ForMember(dest => dest.PortfolioTypeName, o => o.MapFrom(src => src.PortfolioType.Name));
            //.ReverseMap();
    }
}

-----编辑-----

在阅读了Lucian Bargaoanu评论中的文档链接后,我认为最好稍微改变一下这个答案。

无参数services.AddAutoMapper()(具有@saineshwar答案)不再工作(至少对我来说)。但是如果你使用NuGet程序集AutoMapper.Extensions.Microsoft。DependencyInjection,框架能够检查所有扩展AutoMapper的类。配置文件(像我的,MappingProfile)。

因此,在我的例子中,类属于同一个正在执行的程序集,服务注册可以缩短为services.AddAutoMapper(System.Reflection.Assembly.GetExecutingAssembly()); (一种更优雅的方法是使用这种编码的无参数扩展)。

谢谢,卢西恩!

在。net 6中,你需要在Program.cs文件中添加以下内容:

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

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

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

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

使用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);
        }
    }