【发布时间】:2017-05-16 05:08:09
【问题描述】:
只是为了测试,我不想从 StartUp.cs 文件进行依赖注入。 如何从 EF Core DBContext 获取 IHostingEnvironment。
我采用了一个带有空模板的新 asp.net 核心项目。我创建了一个 dbcontext,如下所示。我想使用 Environment.ContentRootPath 而不是 Directory.GetCurrentDirectory()。但我不想从 Startup.cs 进行任何注入。
public class MyDBContext: DbContext
{
public IConfigurationRoot Configuration { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "..\\..\\.."))
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("SQLCN"));// @"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
}
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Lesson> Lessons { get; set; }
}
如果我在 dbcontext 构造函数中添加 IHostingEnvironment,如下所示,
public class MyDBContext: DbContext
{
private readonly IHostingEnvironment env;
public MyDBContext(IHostingEnvironment env) : base()
{
this.env = env;
}
public IConfigurationRoot Configuration { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder()
.SetBasePath(this.env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("SQLCN"));// @"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
}
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Lesson> Lessons { get; set; }
}
从 Package-Manager 控制台添加迁移时出现以下错误。
PM> Add-Migration InitMyDBContext
在“MyDBContext”上找不到无参数构造函数。要么添加一个 无参数构造函数到“MyDBContext”或添加一个实现 'IDbContextFactory' 在同一个程序集中 'MyDBContext'。
【问题讨论】:
-
提供问题和预期行为的minimal reproducible example,以便得出解决方案。
-
亲爱的@Nkosi,我更新了我的问题。提前致谢。本题不针对生产问题,仅供学习。
-
我仍然不清楚你不想从启动时进行任何注入是什么意思?请澄清这一点。您实际上可以将 IHostingEnvironment 直接注入到 dbcontext 的构造函数中。
-
@Nkosi,如何将 IHostingEnvironment 直接注入到 dbcontext 中?
-
原问题回答正确。应该为迁移错误发布新问题,因为这是一个不同的问题。我在 2.2 中发现要让迁移很好地发挥作用,我必须从找到 Startup 的项目中运行迁移命令,并且我的上下文也驻留在那里。
标签: c# entity-framework asp.net-core entity-framework-core