Restaurants WebAPI(二)——DTO/CQRS
文章目录
- 项目地址
- 一、DTO
- 1.1 创建Restaurant的Dto
- 1.2 修改之前未使用Dto的接口
- 1.2.1 修改GetRestaurantByIdUseCase
- 1.2.2 修改IGetRestaurantByIdUseCase接口
- 1.2.3 再次请求接口
- 1.3 显示Dish List
- 1.3.1创建DishDto
- 1.3.2 在RestaurantDto里添加DishDto
- 1.3.3 使用Include添加Dishes
项目地址
- 教程作者:Jakub Kozera
- 教程地址UD:
https://www.csdn.com/course/aspnet-core-web-api-clean-architecture-azure/learn/lecture/42032838#overview
- 代码仓库地址:
- 所用到的框架和插件:
.net 8
一、DTO
避免直接暴露数据库实体
1.1 创建Restaurant的Dto
- 在Restaurants.Application创建
Dtos文件夹
; - 创建
RestaurantDto.cs
,FromRestaurant静态方法,只是为了包装真正的实体类只返回需要的属性;
using Restaurants.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace Restaurants.Application.Dtos
{public class RestaurantDto{public int Id { get; set; }public string Name { get; set; } = default!;public string Description { get; set; } = default!;public string Category { get; set; } = default!;public bool HasDelivery { get; set; }public string? City { get; set; }public string? Street { get; set; }public string? ZipCode { get; set; }public List<DishDto> Dishes { get; set; } = new List<DishDto>();public static RestaurantDto FromRestaurant(Restaurant restaurant){return new RestaurantDto(){Id = restaurant.Id,Name = restaurant.Name,Description = restaurant.Description,Category = restaurant.Category,HasDelivery = restaurant.HasDelivery,City = restaurant.Address?.City,Street = restaurant.Address?.Street,ZipCode = restaurant.Address?.ZipCode,};}}
}