使用ASP.NET Core 3.x 構建 RESTful API P13 P14 獲取父子關係的資源
博客園文章id:12674187
父子關係的數據在API中的表現(第一種)情況
舉例: 一個公司一般有多個員工,即一對多關係,那麼我們怎麼通過API來表現這種關係呢?
對外模型Dto的編寫
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; }
}
}
AutoMapper對象映射關係
using System;
using AutoMapper;
using Routine.Api.Entitle;
using Routine.Api.Models;
namespace Routine.Api.Profiles
{
/// <summary>
/// 配置 Employee 和 EmployeeDto 對象間的映射關係
/// </summary>
public class EmployeeProfile:Profile
{
public EmployeeProfile()
{
CreateMap<Employee, EmployeeDto>()
.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=>DateTime.Now.Year - src.DateOfBirth.Year)) //年齡
;
}
}
}
API的編寫
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Routine.Api.Entitle;
using Routine.Api.Models;
using Routine.Api.Services;
namespace Routine.Api.Controllers
{
[ApiController]
[Route("api/companies/{companyId}/employees")]
public class EmployeesController:ControllerBase
{
private readonly IMapper _mapper;
private readonly ICompanyRepository _companyRepository;
public EmployeesController(IMapper mapper,ICompanyRepository companyRepository)
{
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
_companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository));
}
[HttpGet]
public async Task<ActionResult<IEnumerable<EmployeeDto>>> GetEmployeeForCompany(Guid companyId)
{
if (! await this._companyRepository.CompanyExistsAsync(companyId))
{
return NotFound();
}
var employees = await this._companyRepository.GetEmployeeAsync(companyId);
return Ok(this._mapper.Map<IEnumerable<EmployeeDto>>(employees));
}
}
}
在調用之前我們還需要豐富一下 RoutineDbContext.cs
類中的種子數據,種子數據如下:
//Company表種子數據
modelBuilder.Entity<Company>().HasData(
new 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",
},
new Company
{
Id = Guid.Parse("5efc910b-2f45-43df-afae-620d40542853"),
Name = "Alipapa",
Introduction = "Fubao Company",
},
new Company
{
Id = Guid.Parse("bbdee09c-089b-4d30-bece-44df59237100"),
Name = "Tencent",
Introduction = "From Shenzhen",
},
new Company
{
Id = Guid.Parse("6fb600c1-9011-4fd7-9234-881379716400"),
Name = "Baidu",
Introduction = "From Beijing",
},
new Company
{
Id = Guid.Parse("5efc910b-2f45-43df-afae-620d40542800"),
Name = "Adobe",
Introduction = "Photoshop?",
},
new Company
{
Id = Guid.Parse("bbdee09c-089b-4d30-bece-44df59237111"),
Name = "SpaceX",
Introduction = "Wow",
},
new Company
{
Id = Guid.Parse("6fb600c1-9011-4fd7-9234-881379716411"),
Name = "AC Milan",
Introduction = "Football Club",
},
new Company
{
Id = Guid.Parse("5efc910b-2f45-43df-afae-620d40542811"),
Name = "Suning",
Introduction = "From Jiangsu",
},
new Company
{
Id = Guid.Parse("bbdee09c-089b-4d30-bece-44df59237122"),
Name = "Twitter",
Introduction = "Blocked",
},
new Company
{
Id = Guid.Parse("6fb600c1-9011-4fd7-9234-881379716422"),
Name = "Youtube",
Introduction = "Blocked",
},
new Company
{
Id = Guid.Parse("5efc910b-2f45-43df-afae-620d40542822"),
Name = "360",
Introduction = "- -",
},
new Company
{
Id = Guid.Parse("bbdee09c-089b-4d30-bece-44df59237133"),
Name = "Jingdong",
Introduction = "Brothers",
},
new Company
{
Id = Guid.Parse("6fb600c1-9011-4fd7-9234-881379716433"),
Name = "NetEase",
Introduction = "Music?",
},
new Company
{
Id = Guid.Parse("5efc910b-2f45-43df-afae-620d40542833"),
Name = "Amazon",
Introduction = "Store",
},
new Company
{
Id = Guid.Parse("bbdee09c-089b-4d30-bece-44df59237144"),
Name = "AOL",
Introduction = "Not Exists?",
},
new Company
{
Id = Guid.Parse("6fb600c1-9011-4fd7-9234-881379716444"),
Name = "Yahoo",
Introduction = "Who?",
},
new Company
{
Id = Guid.Parse("5efc910b-2f45-43df-afae-620d40542844"),
Name = "Firefox",
Introduction = "Is it a company?",
});
//Employee 表種子數據
modelBuilder.Entity<Employee>().HasData(
new Employee
{
Id = Guid.Parse("4b501cb3-d168-4cc0-b375-48fb33f318a4"),
CompanyId = Guid.Parse("bbdee09c-089b-4d30-bece-44df5923716c"),
DateOfBirth = new DateTime(1976, 1, 2),
EmployeeNo = "MSFT231",
FirstName = "Nick",
LastName = "Carter",
Gender = Gender.男
},
new Employee
{
Id = Guid.Parse("7eaa532c-1be5-472c-a738-94fd26e5fad6"),
CompanyId = Guid.Parse("bbdee09c-089b-4d30-bece-44df5923716c"),
DateOfBirth = new DateTime(1981, 12, 5),
EmployeeNo = "MSFT245",
FirstName = "Vince",
LastName = "Carter",
Gender = Gender.男
},
new Employee
{
Id = Guid.Parse("72457e73-ea34-4e02-b575-8d384e82a481"),
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("7644b71d-d74e-43e2-ac32-8cbadd7b1c3a"),
CompanyId = Guid.Parse("6fb600c1-9011-4fd7-9234-881379716440"),
DateOfBirth = new DateTime(1977, 4, 6),
EmployeeNo = "G097",
FirstName = "Kevin",
LastName = "Richardson",
Gender = Gender.男
},
new Employee
{
Id = Guid.Parse("679dfd33-32e4-4393-b061-f7abb8956f53"),
CompanyId = Guid.Parse("5efc910b-2f45-43df-afae-620d40542853"),
DateOfBirth = new DateTime(1967, 1, 24),
EmployeeNo = "A009",
FirstName = "卡",
LastName = "裏",
Gender = Gender.女
},
new Employee
{
Id = Guid.Parse("1861341e-b42b-410c-ae21-cf11f36fc574"),
CompanyId = Guid.Parse("5efc910b-2f45-43df-afae-620d40542853"),
DateOfBirth = new DateTime(1957, 3, 8),
EmployeeNo = "A404",
FirstName = "Not",
LastName = "Man",
Gender = Gender.男
});
數據準備好了之後,我們還需要進行一下數據的遷移操作,我們需要在Nuget
控制檯中執行下列命令,進行種子數據的遷移工作.
add-Migration AddEmployeeData
遷移完成只有會在項目中生成一下遷移描述的文件.
完成上述步驟之後,我們啓動項目完成遷移,並驗證在API中查詢父子關係的數據是否正確.
遷移到Employee表的數據信息如下:
查詢指定公司下的所有員工,API調用結果:
父子關係的數據在API中的表現(第二種)情況
我們也可以編寫查詢指定公司下的指定員工信息的接口,代碼如下:
[HttpGet("{employeeId}")]
public async Task<ActionResult<EmployeeDto>> GetEmployeeForCompany(Guid companyId, Guid employeeId)
{
if (!await this._companyRepository.CompanyExistsAsync(companyId))
{
return NotFound();
}
if (employee == null)
{
return NotFound();
}
var employee = await this._companyRepository.GetEmployeeAsync(companyId,employeeId);
return Ok(this._mapper.Map<EmployeeDto>(employee));
}
查詢指定公司下的指定員工,API調用結果: