試圖按如下方式實施IDbContextFactory
。並得到了在線路return Create(options.ContentRootPath, options.EnvironmentName);
和var optionsBuilder = new DbContextOptionsBuilder<MyProjContext>();
以下錯誤運行時,以下PM
命令無法實現用於實體框架數據遷移的IDbContextFactory
PM> add-migration MyMigration -context MyProjContext
錯誤
An error occurred while calling method 'ConfigureServices' on startup class 'Startup'. Consider using IDbContextFactory to override the initialization of the DbContext at design-time. Error: Could not find 'UserSecretsIdAttribute' on assembly 'ef, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. System.InvalidOperationException: Could not find a connection string named '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; }
...
}
}