EFCore 套件安裝
使用 EFCore 相關 nuget 套件,分別為
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tool
安裝 Microsoft.EntityFrameworkCore.Tool 才能使用 Scaffold-DbContext
套件管理器主控台內進行安裝
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
使用 Scaffold-DbContext 來建立 entity
在 [套件管理器主控台] 內輸入下列語法
Scaffold-DbContext "Server=.;Database=AdventureWorks2022;Trusted_Connection=True;TrustServerCertificate=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force
參數說明- -OutputDir:產生的 Model 要放在哪一個資料夾內
- -Force :強制覆蓋
Scaffold-DbContext 建立 entity 後,可以在 DbContext OnConfiguring() 內發現連線字串警告
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see https://go.microsoft.com/fwlink/?LinkId=723263.
=> optionsBuilder.UseSqlServer("Server=.;Database=AdventureWorks2022;Trusted_Connection=True;TrustServerCertificate=true");
使用 appsetings.json 來儲存資料庫連線
原本是想找 [JSON 檔案] 範本來新增 appsettings.json 檔案,但是發現在 Console Project 內不會有它,最後是選擇 [JavaScript JSON 組態檔] 來新增並進行修改,參考資料 - can't add appsettings.json
把 appsettings.json 檔案屬性 [複製到輸出目錄] 修改為 [永遠複製]
把連線字串從 OnConfiguring 內移至 appsettings.json 內
{
"ConnectionStrings": {
"SqlServer": "Server=.;Database=AdventureWorks2022;Trusted_Connection=True;TrustServerCertificate=true"
}
}
主程式
在 Console Project 內安裝
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.Json
下述程式會從 appsettings.json 內抓出連線字串,並把連線字串塞進 DbContext 內
using CRUDSimple.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace CRUDSimple
{
internal class Program
{
static void Main(string[] args)
{
string connectionString = GetConnectionString();
var options = new DbContextOptionsBuilder<AdventureWorks2022Context>()
.UseSqlServer(connectionString)
.Options;
using (AdventureWorks2022Context dbContext = new AdventureWorks2022Context(options))
{
var source = dbContext.Employees
.OrderBy(e => e.HireDate)
.Take(10)
.ToList();
foreach (Employee e in source)
Console.WriteLine(e.JobTitle);
}
}
private static string GetConnectionString()
{
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
// 從 appsettings 取得連線字串
// 寫法一
// string connectionString = configuration.GetSection("ConnectionString").GetSection("SqlServer").Value;
// 寫法二
string connectionString = configuration.GetConnectionString("SqlServer");
return connectionString;
}
}
}
- 參考資料
- ASP.NET Core - (DB-First) Scaffold-DbContext的錯誤訊息
- [SQL Server] A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - 此憑證鏈結是由不受信任的授權單位發出的。)
- Using an ‘appsettings.json’ file with a C# console app
- ASP.NET Core .NET 5 打造WebAPI入門教學(2_1) - 資料庫連線設定 Database First,Scaffold-DbContext Build Failed解決方式
- Scaffolding (反向工程)
- 如何使用組態 Microsoft.Extensions.Configuration
沒有留言:
張貼留言