如何在ASP.NET Core中设置Automapper
我在.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?
我知道了!详细信息如下:
I figured it out! Here's the details:
-
通过 NuGet 将主AutoMapper软件包添加到您的解决方案中.
Add the main AutoMapper Package to your solution via NuGet.
通过 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入手!我欢迎任何反馈或批评,因为我还是.NET世界的新人!
I hope this helps someone starting fresh with ASP.NET Core! I welcome any feedback or criticisms as I'm still new to the .NET world!