我想到了!详细信息如下:
- 通过NuGet将主要的AutoMapper软件包添加到您的解决方案中。
为映射配置文件创建一个新类。(我在主解决方案目录中创建了一个名为的类,
MappingProfile.cs
并添加了以下代码。)我将使用User
andUserDto
对象作为示例。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 :public void ConfigureServices(IServiceCollection services) {// .... Ignore pre before this
// Auto Mapper Configurations
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});IMapper mapper = mappingConfig.CreateMapper();services.AddSingleton(mapper);services.AddMvc();
}
要在代码中调用映射的对象,请执行以下 *** 作:
public class UserController : Controller {// Create a field to store the mapper objectprivate readonly IMapper _mapper;// Assign the object in the constructor for dependency injectionpublic UserController(IMapper mapper) { _mapper = mapper;}public async Task<IActionResult> Edit(string id) { // Instantiate source object // (Get it from the database or whatever your pre 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世界的新手!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)