【发布时间】:2017-08-13 21:47:52
【问题描述】:
尝试如下实现IDbContextFactory。在运行PM 命令时,在return Create(options.ContentRootPath, options.EnvironmentName); 和var optionsBuilder = new DbContextOptionsBuilder<MyProjContext>(); 行出现以下错误
PM> add-migration MyMigration -context MyProjContext
错误
在启动类“Startup”上调用方法“ConfigureServices”时出错。考虑使用 IDbContextFactory 在设计时覆盖 DbContext 的初始化。错误:在程序集“ef,版本=1.0.0.0,文化=中性,PublicKeyToken=adb9793829ddae60”上找不到“UserSecretsIdAttribute”。 System.InvalidOperationException:找不到名为“MyProjContext”的连接字符串。 ....
注意MyProjCnotext.cs和MyProjContextFactory.cs文件都在MyProj\Models文件夹中
MyProjContextFactory 类
public class MyProjContextFactory : IDbContextFactory<MyProjContext>
{
public MyProjContext Create()
{
var environmentName = Environment.GetEnvironmentVariable("Hosting:Environment");
return Create(Directory.GetCurrentDirectory(), environmentName);
}
public MyProjContext Create(DbContextFactoryOptions options)
{
return Create(options.ContentRootPath, options.EnvironmentName);
}
public MyProjContext Create(string basePath, string environmentName)
{
var builder = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environmentName}.json", true)
.AddEnvironmentVariables();
var Configuration = builder.Build();
var connectionName = nameof(MyProjContext);
var connectionString = Configuration.GetConnectionString(connectionName);
if (String.IsNullOrWhiteSpace(connectionString) == true)
throw new InvalidOperationException($"Could not find a connection string named '{connectionName}'.");
// init SQL server
var optionsBuilder = new DbContextOptionsBuilder<MyProjContext>();
optionsBuilder.UseSqlServer(connectionString);
return new MyProjContext(optionsBuilder.Options);
}
}
MyProjContext.cs
namespace MyProj.Models
{
public class MyProjContext : DbContext
{
public MyProjContext(DbContextOptions<MyProjContext> options) : base(options)
{
}
public DbSet<Table1> Table1 { get; set; }
public DbSet<Table2> Table2 { get; set; }
...
}
}
【问题讨论】:
标签: c# entity-framework entity-framework-migrations