在ASP.NET Core MVC 2.2 中使用AutoMapper

芝麻麻雀發表於2019-01-18

AutoMapper doc:http://docs.automapper.org/en/stable/index.html

使用vs 2017 建立一個新專案:Application.Web

使用nuget新增引用:AutoMapper.Extensions.Microsoft.DependencyInjection

依賴項右兩個:

1、註冊AutoMapper服務

在Startup.cs檔案中,找到ConfigureServices方法,在方法的最後新增一行程式碼:

services.AddAutoMapper();

 新增完成後,如下圖所示

2、對映配置檔案

必須在專案中新增對映配置檔案,以便AutoMapper能夠正確的識別要對映的物件

對映配置類要繼承Profile類。當程式第一次執行時,AutoMapper會查詢從Profile類繼承的類並載入配置檔案

AutoMapper能夠自動從源和目標對映相同的名稱屬性

3、新增對映檔案類

對映檔案類:

public class MappingProfiles : Profile
{
    public MappingProfiles()
    {
        CreateMap<Department, DepartmentDTO>().ReverseMap();
    }
}

源和目標類:

    //源
    public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Owner { get; set; }
        public string SecretProperty { get; set; }
    }

    //目標
    public class DepartmentDTO
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Owner { get; set; }
    }

4、新增Controller

在Controllers資料夾中新增一個MyMappingController類

namespace Application.Web.Controllers
{
    public class MyMappingController : Controller
    {
        private readonly IMapper _mapper;
        private readonly Department sampleDepartment;
        public MyMappingController(IMapper mapper)
        {
            _mapper = mapper;
            sampleDepartment = new Department
            {
                Name = "department1", Id = 1, Owner = "ABC", SecretProperty = "Very secret property"
            };
        }
        [HttpGet]
        public ActionResult<DepartmentDTO> Index()
        {
            return _mapper.Map<DepartmentDTO>(sampleDepartment);
        }
    }
}

5、執行專案看結果

執行專案,使用postman訪問我們的專案,可以看到返回的json資料沒有SecretProperty 屬性的值,其他的資料都有值

6、深入使用

在上面的例子中,使用AutoMapper實現了簡單的一對一的對映,但是AutoMapper也可用於物件擴充套件或從物件中包含物件的複雜情況。

下面我們將使用引入Person類和PersonDTO類,Person類中包含一個為Address的屬性。而Address是一個類型別。在PersonDTO類中,只有一個City的屬性。我們將使用AutoMapper實現從複雜物件到一個簡單物件的對映。

實現類如下:

namespace Application.Web.Models
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Sex { get; set; }
        public int Age { get; set; }
        public Address Address { get; set; }
    }
    public class Address
    {
        public string HouseNumber { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
    }
    public class PersonDTO
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Sex { get; set; }
        public int Age { get; set; }
        public string City { get; set; }
    }
}

 7、修改MappingProfiles對映類

public class MappingProfiles : Profile
{
    public MappingProfiles()
    {
        CreateMap<Department, DepartmentDTO>().ReverseMap();
        CreateMap<Person, PersonDTO>()
            .ForMember(dest => dest.City, opts => opts.MapFrom(src => src.Address.City))
            .ReverseMap();
    }
}

8、在MyMappingController類中新增對Person的對映方法,修改後程式碼如下:

namespace Application.Web.Controllers
{
    public class MyMappingController : Controller
    {
        private readonly IMapper _mapper;
        private readonly Department sampleDepartment;
        private readonly Person samplePerson;
        public MyMappingController(IMapper mapper)
        {
            _mapper = mapper;
            sampleDepartment = new Department
            {
                Name = "department1", Id = 1, Owner = "ABC", SecretProperty = "Very secret property"
            };
            samplePerson = new Person()
            {
                FirstName = "John",
                LastName = "Doe",
                Age = 30,
                Sex = "Male",
                Address = new Address()
                {
                    City = "New York City",
                    HouseNumber = "10",
                    State = "NY",
                    ZipCode = "999999"
                }
            };
        }
        [HttpGet]
        public ActionResult<DepartmentDTO> Index()
        {
            return _mapper.Map<DepartmentDTO>(sampleDepartment);
        }
        public ActionResult<PersonDTO> GetPerson()
        {
            return _mapper.Map<PersonDTO>(samplePerson);
        }
    }
}

9、執行專案看結果

通過結果可以看到,City屬性成功的使用了Address屬性內的City屬性值。


相關文章