2017-08-12 164 views
0

试图按如下方式实施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.csMyProjContextFactory.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; } 
    ... 
} 
} 

回答

0

你抛出一个异常:throw new InvalidOperationException($"Could not find a connection string named '{connectionName}'.");

添加在appsettings.json和appsettings.Development.json:

{ 
    ... 
    "ConnectionStrings": { 
     "MyProjContext": "..." 
    } 
}