diff --git a/README.md b/README.md index 89f3693..7574ef5 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ __ASP.NET Core 3.0 实现 RESTful API 的学习笔记__

跟随杨旭老师(solenovex)的[博客](https://www.cnblogs.com/cgzl/p/11814971.html)与[视频](https://www.bilibili.com/video/av77957694?from=search&seid=17664776753878261104)课程,学习 RESTful API 在ASP.NET Core 3.0 上的实现。
-包含课程中搭建的项目与部分笔记,当前更新到`视频P8` 。 +包含课程中搭建的项目与部分笔记,此项目的内容更新到视频 P14 。


非常感谢杨老师 🤗
diff --git a/Routine/Routine.APi/Controllers/CompaniesController.cs b/Routine/Routine.APi/Controllers/CompaniesController.cs index 12fb555..7bd5978 100644 --- a/Routine/Routine.APi/Controllers/CompaniesController.cs +++ b/Routine/Routine.APi/Controllers/CompaniesController.cs @@ -1,4 +1,6 @@ -using Microsoft.AspNetCore.Mvc; +using AutoMapper; +using Microsoft.AspNetCore.Mvc; +using Routine.APi.Models; using Routine.APi.Services; using System; using System.Collections.Generic; @@ -55,40 +57,46 @@ namespace Routine.APi.Controllers public class CompaniesController:ControllerBase { private readonly ICompanyRepository _companyRepository; + private readonly IMapper _mapper; - public CompaniesController(ICompanyRepository companyRepository) + public CompaniesController(ICompanyRepository companyRepository,IMapper mapper) { - this._companyRepository = companyRepository ?? + _companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository)); + _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); } [HttpGet] - public async Task GetCompanies() + public async Task GetCompanies() //Task = Task>> { var companies = await _companyRepository.GetCompaniesAsync(); - return Ok(companies); //OK() 返回状态码200 + + //不使用 AutoMapper + //var companyDtos = new List(); + //foreach(var company in companies) + //{ + // companyDtos.Add(new CompanyDto + // { + // Id = company.Id, + // Name = company.Name + // }); + //} + + //使用 AutoMapper + var companyDtos = _mapper.Map>(companies); + + return Ok(companyDtos); //OK() 返回状态码200 } [HttpGet("{companyId}")] //还可用 [Route("{companyId}")] public async Task GetCompany(Guid companyId) { - //不适合高并发的方法: - //var exist = await _companyRepository.CompanyExistsAsync(companyId); - //if (!exist) - //{ - // return NotFound(); //返回状态码404 - //} - //var company = await _companyRepository.GetCompanyAsync(companyId); - //return Ok(company); - // - - //略有改善的方法: var company = await _companyRepository.GetCompanyAsync(companyId); if (company == null) { return NotFound(); //返回状态码404 } - return Ok(company); + return Ok(_mapper.Map(company)); } } diff --git a/Routine/Routine.APi/Controllers/EmployeesController.cs b/Routine/Routine.APi/Controllers/EmployeesController.cs new file mode 100644 index 0000000..d597ecf --- /dev/null +++ b/Routine/Routine.APi/Controllers/EmployeesController.cs @@ -0,0 +1,61 @@ +using AutoMapper; +using Microsoft.AspNetCore.Mvc; +using Routine.APi.Entities; +using Routine.APi.Models; +using Routine.APi.Services; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Routine.APi.Controllers +{ + [ApiController] + [Route("api/companies/{companyId}/employees")] + public class EmployeesController : ControllerBase + { + private readonly ICompanyRepository _companyRepository; + private readonly IMapper _mapper; + + public EmployeesController(ICompanyRepository companyRepository, IMapper mapper) + { + _companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository)); + _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); + + } + + [HttpGet] + public async Task GetEmployeesForCompany(Guid companyId) + { + if (await _companyRepository.CompanyExistsAsync(companyId)) + { + var employees = await _companyRepository.GetEmployeesAsync(companyId); + var employeeDtos = _mapper.Map>(employees); + return Ok(employeeDtos); + } + else + { + return NotFound(); + } + } + + [HttpGet("{employeeId}")] + public async Task GetEmployeesForCompany(Guid companyId,Guid employeeId) + { + if (await _companyRepository.CompanyExistsAsync(companyId)) + { + var employee = await _companyRepository.GetEmployeeAsync(companyId,employeeId); + if (employee == null) + { + return NotFound(); + } + var employeeDto = _mapper.Map(employee); + return Ok(employeeDto); + } + else + { + return NotFound(); + } + } + } +} diff --git a/Routine/Routine.APi/Data/RoutineDbContext.cs b/Routine/Routine.APi/Data/RoutineDbContext.cs index 34bfd51..b0a2e9f 100644 --- a/Routine/Routine.APi/Data/RoutineDbContext.cs +++ b/Routine/Routine.APi/Data/RoutineDbContext.cs @@ -10,7 +10,7 @@ namespace Routine.APi.Data public class RoutineDbContext : DbContext { //调用并获取父类的options - public RoutineDbContext(DbContextOptionsoptions):base(options) + public RoutineDbContext(DbContextOptions options) : base(options) { } @@ -21,10 +21,10 @@ public RoutineDbContext(DbContextOptionsoptions):base(options) protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().Property(x => x.Name).IsRequired().HasMaxLength(100); - modelBuilder.Entity().Property(x=>x.Introduction).HasMaxLength(500); - modelBuilder.Entity().Property(x=>x.EmployeeNo).IsRequired().HasMaxLength(10); - modelBuilder.Entity().Property(x=>x.FirstName).IsRequired().HasMaxLength(50); - modelBuilder.Entity().Property(x=>x.LastName).IsRequired().HasMaxLength(50); + modelBuilder.Entity().Property(x => x.Introduction).HasMaxLength(500); + modelBuilder.Entity().Property(x => x.EmployeeNo).IsRequired().HasMaxLength(10); + modelBuilder.Entity().Property(x => x.FirstName).IsRequired().HasMaxLength(50); + modelBuilder.Entity().Property(x => x.LastName).IsRequired().HasMaxLength(50); modelBuilder.Entity() //指明一对多关系(可省略) .HasOne(x => x.Company) @@ -33,26 +33,89 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasForeignKey(x => x.CompanyId) //删除Company时如果有Employee,则无法删除 .OnDelete(DeleteBehavior.Restrict); + //种子数据 modelBuilder.Entity().HasData( - new Company + new Company { - Id=Guid.Parse("bbdee09c-089b-4d30-bece-44df5923716c"), - Name="Microsoft", - Introduction="Great Company" + Id = Guid.Parse("bbdee09c-089b-4d30-bece-44df5923716c"), + Name = "Microsoft", + Introduction = "Great Company" }, new Company { - Id=Guid.Parse("6fb600c1-9011-4fd7-9234-881379716440"), - Name="Google", - Introduction="Don't be evil" + Id = Guid.Parse("6fb600c1-9011-4fd7-9234-881379716440"), + Name = "Google", + Introduction = "Don't be evil" }, new Company { - Id=Guid.Parse("5efc910b-2f45-43df-afee-620d40542853"), - Name="Alipapa", - Introduction="Fubao Company" + Id = Guid.Parse("5efc910b-2f45-43df-afee-620d40542853"), + Name = "Alipapa", + Introduction = "Fubao Company" + } + ); + modelBuilder.Entity().HasData( + new Employee + { + Id=Guid.Parse("ca268a19-0f39-4d8b-b8d6-5bace54f8027"), + CompanyId = Guid.Parse("bbdee09c-089b-4d30-bece-44df5923716c"), + DateOfBirth = new DateTime(1955, 10, 28), + EmployeeNo = "M001", + FirstName = "William", + LastName = "Gates", + Gender = Gender.男 + }, + new Employee + { + Id = Guid.Parse("265348d2-1276-4ada-ae33-4c1b8348edce"), + CompanyId = Guid.Parse("bbdee09c-089b-4d30-bece-44df5923716c"), + DateOfBirth = new DateTime(1998, 1, 14), + EmployeeNo = "M024", + FirstName = "Kent", + LastName = "Back", + Gender = Gender.男 + }, + new Employee + { + Id = Guid.Parse("47b70abc-98b8-4fdc-b9fa-5dd6716f6e6b"), + CompanyId = Guid.Parse("6fb600c1-9011-4fd7-9234-881379716440"), + DateOfBirth = new DateTime(1986, 11, 4), + EmployeeNo = "G003", + FirstName = "Mary", + LastName = "King", + Gender = Gender.女 + }, + new Employee + { + Id = Guid.Parse("059e2fcb-e5a4-4188-9b46-06184bcb111b"), + CompanyId = Guid.Parse("6fb600c1-9011-4fd7-9234-881379716440"), + DateOfBirth = new DateTime(1977, 4, 6), + EmployeeNo = "G007", + FirstName = "Kevin", + LastName = "Richardson", + Gender = Gender.男 + }, + new Employee + { + Id = Guid.Parse("a868ff18-3398-4598-b420-4878974a517a"), + CompanyId = Guid.Parse("5efc910b-2f45-43df-afee-620d40542853"), + DateOfBirth = new DateTime(1964, 9, 10), + EmployeeNo = "A001", + FirstName = "Jack", + LastName = "Ma", + Gender = Gender.男 + }, + new Employee + { + Id = Guid.Parse("2c3bb40c-5907-4eb7-bb2c-7d62edb430c9"), + CompanyId = Guid.Parse("5efc910b-2f45-43df-afee-620d40542853"), + DateOfBirth = new DateTime(1997, 2, 6), + EmployeeNo = "A201", + FirstName = "Lorraine", + LastName = "Shaw", + Gender = Gender.女 } - ); + ); } } } diff --git a/Routine/Routine.APi/Migrations/20200111083647_AddEmployeeData.Designer.cs b/Routine/Routine.APi/Migrations/20200111083647_AddEmployeeData.Designer.cs new file mode 100644 index 0000000..aeadc88 --- /dev/null +++ b/Routine/Routine.APi/Migrations/20200111083647_AddEmployeeData.Designer.cs @@ -0,0 +1,174 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Routine.APi.Data; + +namespace Routine.APi.Migrations +{ + [DbContext(typeof(RoutineDbContext))] + [Migration("20200111083647_AddEmployeeData")] + partial class AddEmployeeData + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "3.1.0") + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("Routine.APi.Entities.Company", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Introduction") + .HasColumnType("nvarchar(500)") + .HasMaxLength(500); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(100)") + .HasMaxLength(100); + + b.HasKey("Id"); + + b.ToTable("Companies"); + + b.HasData( + new + { + Id = new Guid("bbdee09c-089b-4d30-bece-44df5923716c"), + Introduction = "Great Company", + Name = "Microsoft" + }, + new + { + Id = new Guid("6fb600c1-9011-4fd7-9234-881379716440"), + Introduction = "Don't be evil", + Name = "Google" + }, + new + { + Id = new Guid("5efc910b-2f45-43df-afee-620d40542853"), + Introduction = "Fubao Company", + Name = "Alipapa" + }); + }); + + modelBuilder.Entity("Routine.APi.Entities.Employee", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CompanyId") + .HasColumnType("uniqueidentifier"); + + b.Property("DateOfBirth") + .HasColumnType("datetime2"); + + b.Property("EmployeeNo") + .IsRequired() + .HasColumnType("nvarchar(10)") + .HasMaxLength(10); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("nvarchar(50)") + .HasMaxLength(50); + + b.Property("Gender") + .HasColumnType("int"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("nvarchar(50)") + .HasMaxLength(50); + + b.HasKey("Id"); + + b.HasIndex("CompanyId"); + + b.ToTable("Employees"); + + b.HasData( + new + { + Id = new Guid("ca268a19-0f39-4d8b-b8d6-5bace54f8027"), + CompanyId = new Guid("bbdee09c-089b-4d30-bece-44df5923716c"), + DateOfBirth = new DateTime(1955, 10, 28, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "M001", + FirstName = "William", + Gender = 1, + LastName = "Gates" + }, + new + { + Id = new Guid("265348d2-1276-4ada-ae33-4c1b8348edce"), + CompanyId = new Guid("bbdee09c-089b-4d30-bece-44df5923716c"), + DateOfBirth = new DateTime(1998, 1, 14, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "M024", + FirstName = "Kent", + Gender = 1, + LastName = "Back" + }, + new + { + Id = new Guid("47b70abc-98b8-4fdc-b9fa-5dd6716f6e6b"), + CompanyId = new Guid("6fb600c1-9011-4fd7-9234-881379716440"), + DateOfBirth = new DateTime(1986, 11, 4, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "G003", + FirstName = "Mary", + Gender = 0, + LastName = "King" + }, + new + { + Id = new Guid("059e2fcb-e5a4-4188-9b46-06184bcb111b"), + CompanyId = new Guid("6fb600c1-9011-4fd7-9234-881379716440"), + DateOfBirth = new DateTime(1977, 4, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "G007", + FirstName = "Kevin", + Gender = 1, + LastName = "Richardson" + }, + new + { + Id = new Guid("a868ff18-3398-4598-b420-4878974a517a"), + CompanyId = new Guid("5efc910b-2f45-43df-afee-620d40542853"), + DateOfBirth = new DateTime(1964, 9, 10, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "A001", + FirstName = "Jack", + Gender = 1, + LastName = "Ma" + }, + new + { + Id = new Guid("2c3bb40c-5907-4eb7-bb2c-7d62edb430c9"), + CompanyId = new Guid("5efc910b-2f45-43df-afee-620d40542853"), + DateOfBirth = new DateTime(1997, 2, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "A201", + FirstName = "Lorraine", + Gender = 0, + LastName = "Shaw" + }); + }); + + modelBuilder.Entity("Routine.APi.Entities.Employee", b => + { + b.HasOne("Routine.APi.Entities.Company", "Company") + .WithMany("Employees") + .HasForeignKey("CompanyId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Routine/Routine.APi/Migrations/20200111083647_AddEmployeeData.cs b/Routine/Routine.APi/Migrations/20200111083647_AddEmployeeData.cs new file mode 100644 index 0000000..c2e2d98 --- /dev/null +++ b/Routine/Routine.APi/Migrations/20200111083647_AddEmployeeData.cs @@ -0,0 +1,57 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace Routine.APi.Migrations +{ + public partial class AddEmployeeData : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.InsertData( + table: "Employees", + columns: new[] { "Id", "CompanyId", "DateOfBirth", "EmployeeNo", "FirstName", "Gender", "LastName" }, + values: new object[,] + { + { new Guid("ca268a19-0f39-4d8b-b8d6-5bace54f8027"), new Guid("bbdee09c-089b-4d30-bece-44df5923716c"), new DateTime(1955, 10, 28, 0, 0, 0, 0, DateTimeKind.Unspecified), "M001", "William", 1, "Gates" }, + { new Guid("265348d2-1276-4ada-ae33-4c1b8348edce"), new Guid("bbdee09c-089b-4d30-bece-44df5923716c"), new DateTime(1998, 1, 14, 0, 0, 0, 0, DateTimeKind.Unspecified), "M024", "Kent", 1, "Back" }, + { new Guid("47b70abc-98b8-4fdc-b9fa-5dd6716f6e6b"), new Guid("6fb600c1-9011-4fd7-9234-881379716440"), new DateTime(1986, 11, 4, 0, 0, 0, 0, DateTimeKind.Unspecified), "G003", "Mary", 0, "King" }, + { new Guid("059e2fcb-e5a4-4188-9b46-06184bcb111b"), new Guid("6fb600c1-9011-4fd7-9234-881379716440"), new DateTime(1977, 4, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), "G007", "Kevin", 1, "Richardson" }, + { new Guid("a868ff18-3398-4598-b420-4878974a517a"), new Guid("5efc910b-2f45-43df-afee-620d40542853"), new DateTime(1964, 9, 10, 0, 0, 0, 0, DateTimeKind.Unspecified), "A001", "Jack", 1, "Ma" }, + { new Guid("2c3bb40c-5907-4eb7-bb2c-7d62edb430c9"), new Guid("5efc910b-2f45-43df-afee-620d40542853"), new DateTime(1997, 2, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), "A201", "Lorraine", 0, "Shaw" } + }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DeleteData( + table: "Employees", + keyColumn: "Id", + keyValue: new Guid("059e2fcb-e5a4-4188-9b46-06184bcb111b")); + + migrationBuilder.DeleteData( + table: "Employees", + keyColumn: "Id", + keyValue: new Guid("265348d2-1276-4ada-ae33-4c1b8348edce")); + + migrationBuilder.DeleteData( + table: "Employees", + keyColumn: "Id", + keyValue: new Guid("2c3bb40c-5907-4eb7-bb2c-7d62edb430c9")); + + migrationBuilder.DeleteData( + table: "Employees", + keyColumn: "Id", + keyValue: new Guid("47b70abc-98b8-4fdc-b9fa-5dd6716f6e6b")); + + migrationBuilder.DeleteData( + table: "Employees", + keyColumn: "Id", + keyValue: new Guid("a868ff18-3398-4598-b420-4878974a517a")); + + migrationBuilder.DeleteData( + table: "Employees", + keyColumn: "Id", + keyValue: new Guid("ca268a19-0f39-4d8b-b8d6-5bace54f8027")); + } + } +} diff --git a/Routine/Routine.APi/Migrations/RoutineDbContextModelSnapshot.cs b/Routine/Routine.APi/Migrations/RoutineDbContextModelSnapshot.cs index 8ad1f2d..2dfc59b 100644 --- a/Routine/Routine.APi/Migrations/RoutineDbContextModelSnapshot.cs +++ b/Routine/Routine.APi/Migrations/RoutineDbContextModelSnapshot.cs @@ -94,6 +94,68 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("CompanyId"); b.ToTable("Employees"); + + b.HasData( + new + { + Id = new Guid("ca268a19-0f39-4d8b-b8d6-5bace54f8027"), + CompanyId = new Guid("bbdee09c-089b-4d30-bece-44df5923716c"), + DateOfBirth = new DateTime(1955, 10, 28, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "M001", + FirstName = "William", + Gender = 1, + LastName = "Gates" + }, + new + { + Id = new Guid("265348d2-1276-4ada-ae33-4c1b8348edce"), + CompanyId = new Guid("bbdee09c-089b-4d30-bece-44df5923716c"), + DateOfBirth = new DateTime(1998, 1, 14, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "M024", + FirstName = "Kent", + Gender = 1, + LastName = "Back" + }, + new + { + Id = new Guid("47b70abc-98b8-4fdc-b9fa-5dd6716f6e6b"), + CompanyId = new Guid("6fb600c1-9011-4fd7-9234-881379716440"), + DateOfBirth = new DateTime(1986, 11, 4, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "G003", + FirstName = "Mary", + Gender = 0, + LastName = "King" + }, + new + { + Id = new Guid("059e2fcb-e5a4-4188-9b46-06184bcb111b"), + CompanyId = new Guid("6fb600c1-9011-4fd7-9234-881379716440"), + DateOfBirth = new DateTime(1977, 4, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "G007", + FirstName = "Kevin", + Gender = 1, + LastName = "Richardson" + }, + new + { + Id = new Guid("a868ff18-3398-4598-b420-4878974a517a"), + CompanyId = new Guid("5efc910b-2f45-43df-afee-620d40542853"), + DateOfBirth = new DateTime(1964, 9, 10, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "A001", + FirstName = "Jack", + Gender = 1, + LastName = "Ma" + }, + new + { + Id = new Guid("2c3bb40c-5907-4eb7-bb2c-7d62edb430c9"), + CompanyId = new Guid("5efc910b-2f45-43df-afee-620d40542853"), + DateOfBirth = new DateTime(1997, 2, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), + EmployeeNo = "A201", + FirstName = "Lorraine", + Gender = 0, + LastName = "Shaw" + }); }); modelBuilder.Entity("Routine.APi.Entities.Employee", b => diff --git a/Routine/Routine.APi/Models/CompanyDto.cs b/Routine/Routine.APi/Models/CompanyDto.cs new file mode 100644 index 0000000..fbd5d6d --- /dev/null +++ b/Routine/Routine.APi/Models/CompanyDto.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Routine.APi.Models +{ + public class CompanyDto + { + public Guid Id { get; set; } + public string Name { get; set; } + } +} diff --git a/Routine/Routine.APi/Models/EmployeeDto.cs b/Routine/Routine.APi/Models/EmployeeDto.cs new file mode 100644 index 0000000..9d3d115 --- /dev/null +++ b/Routine/Routine.APi/Models/EmployeeDto.cs @@ -0,0 +1,15 @@ +using System; + +namespace Routine.APi.Models +{ + public class EmployeeDto + { + public Guid Id { get; set; } + public Guid CompanyId { get; set; } + public string EmployeeNo { get; set; } + public string Name { get; set; } + public string GenderDisplay { get; set; } + + public int Age { get; set; } + } +} diff --git a/Routine/Routine.APi/Profiles/CompanyProfile.cs b/Routine/Routine.APi/Profiles/CompanyProfile.cs new file mode 100644 index 0000000..8de6ccc --- /dev/null +++ b/Routine/Routine.APi/Profiles/CompanyProfile.cs @@ -0,0 +1,24 @@ +using AutoMapper; +using Routine.APi.Entities; +using Routine.APi.Models; + +/// +/// AutoMapper 配置文件 +/// +namespace Routine.APi.Profiles +{ + public class CompanyProfile : Profile + { + public CompanyProfile() + { + //原类型Company -> 目标类型CompanyDto + //AutoMapper 基于约定 + //属性名称一致时自动赋值 + //自动忽略空引用 + CreateMap(); + + //手动映射举例,把 Company(src) 的 Name 映射到 CompanyDto(dest) 的 Name + //CreateMap().ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name)); + } + } +} diff --git a/Routine/Routine.APi/Profiles/EmployeeProfile.cs b/Routine/Routine.APi/Profiles/EmployeeProfile.cs new file mode 100644 index 0000000..a676550 --- /dev/null +++ b/Routine/Routine.APi/Profiles/EmployeeProfile.cs @@ -0,0 +1,42 @@ +using AutoMapper; +using Routine.APi.Entities; +using Routine.APi.Models; +using System; + +namespace Routine.APi.Profiles +{ + public class EmployeeProfile : Profile + { + public EmployeeProfile() + { + CreateMap() + .ForMember(dest => dest.Name, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}")) + .ForMember(dest => dest.GenderDisplay, opt => opt.MapFrom(src => src.Gender.ToString())) + .ForMember(dest => dest.Age, opt => opt.MapFrom(src => GetAge(src.DateOfBirth))); + } + + /// + /// 获得年龄 + /// + /// 出生日期 + /// + private int GetAge(DateTime dateOfBirth) + { + DateTime dateOfNow = DateTime.Now; + if (dateOfBirth > dateOfNow) + { + throw new ArgumentOutOfRangeException(nameof(dateOfBirth)); + } + int age = dateOfNow.Year - dateOfBirth.Year; + if (dateOfNow.Month < dateOfBirth.Month) + { + age--; + } + else if (dateOfNow.Month == dateOfBirth.Month && dateOfNow.Day < dateOfBirth.Day) + { + age--; + } + return age; + } + } +} diff --git a/Routine/Routine.APi/Routine.APi.csproj b/Routine/Routine.APi/Routine.APi.csproj index a58de2e..5b98127 100644 --- a/Routine/Routine.APi/Routine.APi.csproj +++ b/Routine/Routine.APi/Routine.APi.csproj @@ -5,6 +5,7 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Routine/Routine.APi/Startup.cs b/Routine/Routine.APi/Startup.cs index f7920e5..626d8ca 100644 --- a/Routine/Routine.APi/Startup.cs +++ b/Routine/Routine.APi/Startup.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using AutoMapper; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; @@ -58,6 +59,9 @@ public void ConfigureServices(IServiceCollection services) // options.ReturnHttpNotAcceptable = true; //}).AddXmlDataContractSerializerFormatters(); + //ʹ AutoMapperɨ赱ǰӦ Assemblies Ѱ AutoMapper ļ + services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); + //AddScoped ÿһ HTTP 󶼻Ὠһµʵ services.AddScoped();