希望获得有关在 .NET 5 Web API 中设置连接字符串的最佳实践的指导。我正在使用 EF Core Power Tools 对数据库模型进行逆向工程,并且我在 appsettings.json 文件中有一个连接字符串。试图弄清楚我应该如何将Microsoft 的 DbContext 配置文档中的步骤与我现有的设置一起应用。
项目设置(为简洁起见)基本上如下所示:
应用设置.json
{
"ConnectionStrings": {
"DefaultConnection": "..."
}
}
启动.cs
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)
{
}
...
}
}
ExampleController.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 刷新模型时,此连接字符串设置都会被覆盖。
有没有更好的例子可以效仿,或者这里最好的方法是什么?谢谢!