【发布时间】:2020-08-27 16:20:32
【问题描述】:
我见过很多 tutorials 解释 .NET core + EF 配置,但没有一个解释如何在 DbContext 中获取 Configuration 实例。
我需要这个的原因是为了获取数据库连接字符串:
namespace Models
{
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite(Configuration.GetConnectionString("BlogDb"));
}
}
我的连接字符串在appsettings.json 文件中:
{
"ConnectionStrings": {
"BlogDB": "Data Source=blogging.db"
}
}
大多数教程在 db 上下文中显示IConfiguration 的实例。我怀疑它是通过构造函数发生的:
private readonly IConfiguration Configuration;
public BlogContext(IConfiguration config) {
Configuration = config;
}
但是,这实际上是如何注入的?
这就是我使用上下文的方式:
public class Seed
{
public static void SeedDatabase()
{
using var db = new BlogContext();
... stuff ...
}
}
我如何真正从设置文件中获取连接字符串?做一些非常简单的事情似乎很混乱,需要做很多工作......
更新
我像这样使用Seed:
public class Program
{
public static void Main(string[] args)
{
Seed.SeedDatabase();
}
}
我如何真正将DbContext 的实例放入SeedDatabase?
【问题讨论】:
标签: c# entity-framework .net-core