iT邦幫忙

2022 iThome 鐵人賽

DAY 5
0

目的

快速對應,不需要寫linq來將資料庫端的model對應到view要用的model

同步更新於個人部落格
Automapper範例

1.建立新專案

選擇ASP.NET Core Web API專案範本,並執行下一步
步驟一

2.設定新的專案

命名你的專案名稱,並選擇專案要存放的位置。
步驟二

3.其他資訊

直接進行下一步
步驟三

4.NuGet加入套件

透過NuGet安裝AutoMapper.Extensions.Microsoft.DependencyInjection
步驟4

5.編輯Program.cs檔案

註冊AutoMapper

//找到所有繼承profile
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

步驟5

6.新增Mappings資料夾與Models資料夾

步驟6

7.在Models資料夾內加入DbModel資料夾與ViewModel資料夾

步驟7

8.加入類別檔

在兩個資料夾內加入同名稱的類別檔案
步驟8

  • DbModel.cs寫入程式碼
    public int Id { get; set; }
    public string? Name { get; set; }
    public int Age { get; set; }
    public DateTime CreatedDate { get; set; }

可能會有些人問?是什麼,這是因為建立.net6專案預設會開啟判斷值可能為null的警告訊息,可以加上?代表允許此屬性為null,會建議在建構子時提供預設值,來避免嘗試對null值做處理的exception。

步驟8-1

  • ViewModel.cs寫入程式
    public ViewModel() { 
    Name = string.Empty;
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

在建構子提供預設值後,來避免對null做處理。

步驟8-2

9.加入類別檔

在Mappings資料夾內加入名稱為ExampleMapping的類別檔
步驟9-1

  • 寫入程式
    在新增的ExampleMapping.cs檔案內寫入程式碼
using AutoMapper;
using AutoMapperExample.Models.DbModel;
using AutoMapperExample.Models.ViewModel;

namespace AutoMapperExample.Mappings {
  //需要繼承AutoMapper的Profile
  public class ExampleMapping : Profile {
    public ExampleMapping() {
      //來源與目標=>白話文是我要將DbModel對應到ViewModel
      CreateMap<DbModel, ViewModel>();
    }
  }
}

步驟9-2

10.加入檔案

在Controllers加入一個空白的API控制器,並命名為ExampleController.cs
步驟10-1
步驟10-2

  • 寫入程式
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using AutoMapperExample.Models.DbModel;
using AutoMapperExample.Models.ViewModel;
using AutoMapper;

namespace AutoMapperExample.Controllers {
  [Route("api/[controller]")]
  [ApiController]
  public class ExampleController : ControllerBase {

    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;
    }
  }
}

步驟10-3

11.執行結果

可以自動對應到結果了。
範例11-1

範例檔

GitHub


上一篇
[.net 6] MailKit範例
下一篇
[.net 6] BenchmarkDotNet範例
系列文
.net6套件入門30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言