雖然知道 Database First 被移除很久了,但目前專案還是主要使用資料庫為主,所以一直沒有機會使用。
但 Core 至少還是有提供 Scaffold-DbContext 可以使用 :
安裝 Microsoft.EntityFrameworkCore.SqlServer

到 Domain 裡面把 Word Class 刪除,建立 EFModels 資料夾

安裝 Microsoft.EntityFrameworkCore.Tools
有噴錯請求 Vocabulary專案也要裝 Microsoft.EntityFrameworkCore.Tools ,這邊我就不先探討原因了…(裝! 都裝!)

改使用 Package Manager Console 指令產生 Model :

執行
Scaffold-DbContext "Data Source=localhost;Initial Catalog=VocabularyDb;User ID=sa;Password=[你的密碼]" Microsoft.EntityFrameworkCore.SqlServer -OutputDir EFModels

回到 Web 專案,在 Startup 註冊

將連線加到 appsettings.json

回到 WordsController 修改程式 :
[Route("api/[controller]")]
[ApiController]
public class WordsController : ControllerBase
{
private readonly VocabularyDbContext _dbContext;
public WordsController(VocabularyDbContext dbContext)
{
_dbContext = dbContext;
}
[HttpGet]
public IActionResult Get()
{
try
{
var result = _dbContext.Words.ToList();
return Ok(result);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
}
在 資料庫直接添加一筆資料測試

執行 Postman 查詢後可以正常存取(灑花

其他 : 如果資料庫有異動,則在參數多加一個 -f 複寫檔案
Scaffold-DbContext "Data Source=localhost;Initial Catalog=VocabularyDb;User ID=sa;Password=[你的密碼]" Microsoft.EntityFrameworkCore.SqlServer -OutputDir EFModels -f