如何在 ASP.NET Core 中设置 Automapper [英] How to set up Automapper in ASP.NET Core
问题描述
我对 .NET 比较陌生,因此我决定解决 .NET Core 而不是学习旧方法".我找到了一篇关于 为 .NET Core 设置 AutoMapper 的详细文章在这里,但是对于新手有没有更简单的演练?
I'm relatively new at .NET, and I decided to tackle .NET Core instead of learning the "old ways". I found a detailed article about setting up AutoMapper for .NET Core here, but is there a more simple walkthrough for a newbie?
推荐答案
我想通了!详情如下:
通过 NuGet 将主要 AutoMapper 包添加到您的解决方案中.
Add the main AutoMapper Package to your solution via NuGet.
通过 NuGet<,将 AutoMapper 依赖注入包添加到您的解决方案中/a>.
Add the AutoMapper Dependency Injection Package to your solution via NuGet.
为映射配置文件创建一个新类.(我在主解决方案目录中创建了一个名为 MappingProfile.cs
的类并添加以下代码.)我将使用 User
和 UserDto
以对象为例.
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>();
}
}
然后在Startup.cs
中添加AutoMapperConfiguration,如下图:
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 中设置 Automapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!