[AutoMapper]AutoMapper Hello world

 

一、建立新專案

二、NuGet加入套件
透過 NuGet 安裝 AutoMapper.Extensions.Microsoft.DependencyInjection 套件

三、註冊 AutoMapper
於 Program.cs 裡檔案加上如下程式碼

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

四、新增來源的 DbModel 與要對應到的 ViewModel 類別
資料結構如下圖

DbModel.cs

1
2
3
4
5
6
7
8
9
10
namespace WebApplication1.Model
{
public class DbModel
{
public int Id { get; set; }
public string? Name { get; set; }
public int Age { get; set; }
public DateTime CreatedDate { get; set; }
}
}

ViewModel.cs

1
2
3
4
5
6
7
8
9
namespace WebApplication1.Model
{
public class ViewModel
{
public int Id { get; set; }
public string? Name { get; set; }
public int Age { get; set; }
}
}

五、加上 Profile 對應檔
資料結構如下圖

ExampleMapping.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
using AutoMapper;
using WebApplication1.Model;

namespace WebApplication1.Profiles
{
public class ExampleMapping : Profile
{
public ExampleMapping()
{
CreateMap<DbModel, ViewModel>();
}
}
}

六、加入帶有測試資料的 api
資料結構如下圖

ExampleController.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Model;

namespace WebApplication1.Controllers
{
[ApiController]
[Route("[controller]")]
public class ExampleController : Controller
{
private readonly IMapper _mapper;
public ExampleController(IMapper mapper)
{
_mapper = mapper;
}

[HttpGet("Index")]
public IEnumerable<ViewModel> Index()
{
var DbModel = new List<DbModel>();
//新增DbModel的List模擬從資料庫來的資料
DbModel.Add(new DbModel() { Id = 1, Name = "Bill", Age = 18, CreatedDate = DateTime.Now });
DbModel.Add(new DbModel() { Id = 1, Name = "CI-YU", Age = 20, CreatedDate = DateTime.Now });
DbModel.Add(new DbModel() { Id = 1, Name = "Bill Huang", Age = 22, CreatedDate = DateTime.Now });
//將DbModel資料自動與ViewModel做對應(相同名稱的屬性)
var map = _mapper.Map<IEnumerable<ViewModel>>(DbModel);
return map;
}
}
}

七、執行結果

參考資料:
[.net 6] Automapper範例