public ViewModel() {
Name = string.Empty;
}
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
在建構子提供預設值後,來避免對null做處理。
加入類別檔
寫入程式 在新增的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>();
}
}
}
加入檔案
寫入程式
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;
}
}
}