希望獲得有關在 .NET 5 Web API 中設定連接字串的最佳實踐的指導。我正在使用 EF Core Power Tools 對資料庫模型進行逆向工程,并且在 appsettings.json 檔案中有一個連接字串。試圖弄清楚我應該如何將Microsoft 的 DbContext 配置檔案中的步驟應用到我現有的設定中。
專案設定(為簡潔起見縮短)基本上如下所示:
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "..."
}
}
啟動檔案
namespace API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
var builder = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", false, true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
Globals.Configuration = Configuration;
}
}
}
ApplicationDbContext.cs(由 EF Core Power Tools 自動生成)
namespace API.Data
{
public partial class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
...
}
}
示例控制器.cs
namespace API.Controllers
{
[ApiController]
[Route("example")]
public class ExampleController : ControllerBase
{
[HttpGet("test")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<ApiResponse> GetExample()
{
using (var db = new ApplicationDbContext())
{
...
}
}
}
}
現在,該設定本身不起作用(示例控制器將導致“沒有為此 DbContext 配置資料庫提供程式。可以通過覆寫 'DbContext.OnConfiguring' 方法來配置提供程式...”錯誤)。
我一直在通過Connection String在ApplicationDbContext.cs類中添加一個屬性(在它自動生成之后)并在 ConfigureServices 中設定屬性來解決這個問題,Startup.cs如下所示:
ApplicationDbContext.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
這確實允許在using(var db = new ApplicationDbContext() { }整個應用程式中使用,但是每次我使用 EF Core Power Tools 重繪 模型時,此連接字串設定都會被覆寫。
有沒有更好的例子可以遵循,或者這里最好的方法是什么?謝謝!
uj5u.com熱心網友回復:
首先,因為您已將 DB Connection 配置為選項。所以不需要默認建構式ApplicationDbContext
public partial class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
這應該沒問題,如果你想從啟動設定連接字串
現在你已經ApplicationDbContext在啟動時注入了,你可以很容易地將控制器用作依賴注入,而不是創建一個新物件。因為創建新物件需要在該 AppDbContext 上設定連接字串,這不是一個好方法!
[ApiController]
[Route("example")]
public class ExampleController : ControllerBase
{
private readonly ApplicationDbContext _applicationDbContext;
ExampleController (private ApplicationDbContext applicationDbContext) {
_applicationDbContext = applicationDbContext;
}
[HttpGet("test")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<ApiResponse> GetExample()
{
//use db context
var something = _applicationDbContext;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/346737.html
標籤:C# 实体框架 asp.net核心 asp.net-core-webapi ef-power-tools
