私は.NETに比較的慣れていないので、「古い方法」を学ぶ代わりに.NET Coreに取り組むことにしました。ここで.NET Core用のAutoMapperを設定するしかし、初心者向けのもっと簡単なチュートリアルはありますか?
ベストアンサー1
分かりました!詳細は次のとおりです。
メインのAutoMapperパッケージをソリューションに追加するには、ヌゲット。
AutoMapper依存性注入パッケージをソリューションに追加するには、ヌゲット。
マッピング プロファイルの新しいクラスを作成します (メイン ソリューション ディレクトリに というクラスを作成し、次のコードを追加します)。例として、andオブジェクト
MappingProfile.cs
を使用します。User
UserDto
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 code before this // Auto Mapper Configurations var mapperConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); IMapper mapper = mapperConfig.CreateMapper(); services.AddSingleton(mapper); services.AddMvc(); }
コード内でマップされたオブジェクトを呼び出すには、次のようにします。
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! } }