WPF实战项目十二(API篇):配置AutoMapper

1、新建类库WPFProjectShared,在类库下新建文件夹Dtos,新建BaseDto.cs,继承INotifyPropertyChanged,实现通知更新。

cs 复制代码
public class BaseDto : INotifyPropertyChanged
    {
        public int Id { get; set; }

        public event PropertyChangedEventHandler? PropertyChanged;

        /// <summary>
        /// 实现通知更新
        /// </summary>
        /// <param name="propertyName"></param>
        public void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

2、WPFProjectAPI添加引用WPFProjectShared

3、新建待办事项传输实体TodoDto.cs,继承BaseDto.cs

cs 复制代码
/// <summary>
    /// 待办事项传输实体
    /// </summary>
    public class TodoDto : BaseDto
    {
        /// <summary>
        /// 标题
        /// </summary>
        private string title;

        public string Title
        {
            get { return title; }
            set { title = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 内容
        /// </summary>
        private string content;

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

        /// <summary>
        /// 状态
        /// </summary>
        private string status;

        public string Status
        {
            get { return status; }
            set { status = value; OnPropertyChanged(); }
        }

    }

4、在api层引入AutoMapper,并新建文件夹Extensions,新建帮助类AutoMapperProFile.cs,继承ProFile

cs 复制代码
    public class AutoMapperProFile : Profile
    {
        public AutoMapperProFile()
        {
            CreateMap<ToDo, TodoDto>().ReverseMap();
        }
    }

5、在program.cs中注册AutoMapper的服务

cs 复制代码
//注册AutoMapper服务
builder.Services.AddAutoMapper(typeof(AutoMapperProFile));

6、IToDoService.cs修改代码传入ToDoDto,相应的ToDoService.cs的代码也要修改

cs 复制代码
    public interface IToDoService : IBaseService<TodoDto>
    {
        
    }
cs 复制代码
public class ToDoService : IToDoService
    {
        private readonly IUnitOfWork unitOfWork;
        private readonly IMapper mapper;

        public ToDoService(IUnitOfWork unitOfWork, IMapper mapper)
        {
            this.unitOfWork = unitOfWork;
            this.mapper = mapper;
        }

        /// <summary>
        /// 新增待办事项
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResponse> AddEntityAsync(TodoDto model)
        {
            try
            {
                var todo = mapper.Map<ToDo>(model);
                await unitOfWork.GetRepository<ToDo>().InsertAsync(todo);
                if(await unitOfWork.SaveChangesAsync() > 0)
                {
                    return new ApiResponse(true, model);
                }
                else
                {
                    return new ApiResponse(false, "添加数据失败!");
                }
            }
            catch (Exception ex)
            {

                return new ApiResponse(false, ex.Message);
            }
        }
        /// <summary>
        /// 删除待办事项
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResponse> DeleteEntityAsync(int id)
        {
            try
            {
                var repository = unitOfWork.GetRepository<ToDo>();
                var todo = await repository.GetFirstOrDefaultAsync(predicate: t => t.Id.Equals(id));
                repository.Delete(todo);
                if (await unitOfWork.SaveChangesAsync() > 0)
                {
                    return new ApiResponse(true, "删除数据成功!");
                }
                else
                {
                    return new ApiResponse(false, "删除数据失败!");
                }
            }
            catch (Exception ex)
            {

                return new ApiResponse(false, ex.Message);
            }
        }
       /// <summary>
       /// 查询所有数据
       /// </summary>
       /// <returns></returns>
        public async Task<ApiResponse> GetAllAsync()
        {
            try
            {
                var repository = unitOfWork.GetRepository<ToDo>();
                var todo = await repository.GetAllAsync();
                if (todo != null)
                {
                    return new ApiResponse(true, todo);
                }
                else
                {
                    return new ApiResponse(false, "查询数据失败!");
                }
            }
            catch (Exception ex)
            {

                return new ApiResponse(false, ex.Message);
            }
        }

        /// <summary>
        /// 根据Id查询数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResponse> GetSingleAsync(int id)
        {
            try
            {
                var repository = unitOfWork.GetRepository<ToDo>();
                var todo = await repository.GetFirstOrDefaultAsync(predicate: t => t.Id.Equals(id));
                if (todo != null)
                {
                    return new ApiResponse(true, todo);
                }
                else
                {
                    return new ApiResponse(false, $"未查询到Id={id}的数据!");
                }
            }
            catch (Exception ex)
            {

                return new ApiResponse(false, ex.Message);
            }
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResponse> UpdateEntityAsync(TodoDto model)
        {
            try
            {
                var dbTodo = mapper.Map<ToDo>(model);
                var repository = unitOfWork.GetRepository<ToDo>();
                var todo = await repository.GetFirstOrDefaultAsync(predicate: t => t.Id.Equals(dbTodo.Id));
                if (todo != null)
                {
                    todo.Title = dbTodo.Title;
                    todo.Content = dbTodo.Content;
                    todo.Status = dbTodo.Status;
                    todo.UpdateDate = DateTime.Now;
                    repository.Update(todo);
                    if(await unitOfWork.SaveChangesAsync() > 0)
                    {
                        return new ApiResponse(true, "更新数据成功!");
                    }
                    else
                    {
                        return new ApiResponse(true, "更新数据失败!");
                    }
                }
                else
                {
                    return new ApiResponse(false, $"未查询到Id={model.Id}的数据!");
                }
            }
            catch (Exception ex)
            {

                return new ApiResponse(false, ex.Message);
            }
        }
    }

7、F5运行项目

相关推荐
耶啵奶膘1 小时前
uniapp-是否删除
linux·前端·uni-app
王哈哈^_^2 小时前
【数据集】【YOLO】【目标检测】交通事故识别数据集 8939 张,YOLO道路事故目标检测实战训练教程!
前端·人工智能·深度学习·yolo·目标检测·计算机视觉·pyqt
cs_dn_Jie3 小时前
钉钉 H5 微应用 手机端调试
前端·javascript·vue.js·vue·钉钉
开心工作室_kaic3 小时前
ssm068海鲜自助餐厅系统+vue(论文+源码)_kaic
前端·javascript·vue.js
有梦想的刺儿4 小时前
webWorker基本用法
前端·javascript·vue.js
cy玩具4 小时前
点击评论详情,跳到评论页面,携带对象参数写法:
前端
qq_390161775 小时前
防抖函数--应用场景及示例
前端·javascript
John.liu_Test5 小时前
js下载excel示例demo
前端·javascript·excel
Yaml46 小时前
智能化健身房管理:Spring Boot与Vue的创新解决方案
前端·spring boot·后端·mysql·vue·健身房管理
PleaSure乐事6 小时前
【React.js】AntDesignPro左侧菜单栏栏目名称不显示的解决方案
前端·javascript·react.js·前端框架·webstorm·antdesignpro