WPF Practical Study Notes 11 - Configuring AutoMapper

Configure AutoMapper

add nuget package

add automapper

### add files

Create a file

  • MyToDo.Share

./Dtos/BaseDto.cs

./Dtos/ToDoDto.cs

+ MyToDo.who

./Extensions/AutoMapperProfile.cs

BaseDto.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace MyToDo.Share.Dtos
{
    public class BaseDto:INotifyPropertyChanged
    {
        public int Id { get; set; }

        public event PropertyChangedEventHandler? PropertyChanged;

        public void OnPropertyChanged([CallerMemberName] string propertyName="")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

ToDoDto.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyToDo.Share.Dtos
{
    public class ToDoDto:BaseDto
    {
        private string? title;
        private string? content;
        private int status;


        public string? Content { get => content; set { content = value; OnPropertyChanged(); } }

        public int Status { get => status; set { status = value; OnPropertyChanged(); } }
        public string? Title { get => title; set { title = value; OnPropertyChanged(); } }
    }
}

AutoMapperProfile.cs

using System.Runtime.CompilerServices;
using AutoMapper;
using AutoMapper.Configuration;
using MyToDo.Api.Context;
using MyToDo.Share.Dtos;

namespace MyToDo.Api.Extensions
{
    public class AutoMapperProfile:MapperConfigurationExpression
    {
        public AutoMapperProfile()
        {
            CreateMap<Todo, ToDoDto>();

        }
    }
}

dependency injection

In Program.cs var app = builder.Build();add before

//添加AutoMapper
var automapperconfig = new MapperConfiguration(config =>
{
    config.AddProfile(new AutoMapperProfile()) ;
});
builder.Services.AddSingleton(automapperconfig.CreateMapper()) ;

modify function

  • ToDoService.cs

image-20230713220105202

image-20230713220158732

Guess you like

Origin blog.csdn.net/xinzhiya001/article/details/131896706