接下來,加入 ValuesController,為了演練不要花太多時間,這裡我就直接讓我的 Controller 直接摸 EF 的DbContext 了,如果是在正式的專案,我不會這樣做
[Route("[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IDbContextFactory<EmployeeDbContext> _employeeDbContextFactory;
public ValuesController(IDbContextFactory<EmployeeDbContext> employeeDbContextFactory)
{
this._employeeDbContextFactory = employeeDbContextFactory;
}
/// <summary>
/// Get Api
/// </summary>
/// <returns></returns>
// GET api/values
[HttpGet]
public async Task<IActionResult> Get(CancellationToken cancel = default)
{
using (MiniProfiler.Current.Step("查詢資料庫"))
{
await using var db = await this._employeeDbContextFactory.CreateDbContextAsync(cancel);
return this.Ok(await db.Employees.AsTracking().ToListAsync(cancel));
}
}
// POST api/values
[HttpPost]
public async Task<IActionResult> Post(CancellationToken cancel = default)
{
using (MiniProfiler.Current.Step("異動資料庫"))
{
await using var db = await this._employeeDbContextFactory.CreateDbContextAsync(cancel);
var toDb = new Employee
{
Id = Guid.NewGuid(),
CreateAt = DateTimeOffset.Now,
CreateBy = Faker.Name.FullName(),
Age = Faker.RandomNumber.Next(1, 100),
Name = Faker.Name.Suffix(),
};
db.Employees.Add(toDb);
await db.SaveChangesAsync(cancel);
return this.Ok(toDb);
}
}
}