代码之家  ›  专栏  ›  技术社区  ›  Kgn-web

EF Core-连接字符串不能为null

  •  0
  • Kgn-web  · 技术社区  · 7 年前

    我在用 ASP.Net Core 2.1 具有 EF Core 2.1

    在从PMC运行任何迁移时,我得到以下错误

    值不能为空。参数名称:connectionString

    这就是我的上下文类的样子

    public class MyAppContextFactory : IDesignTimeDbContextFactory<MyAppContext>
    {
        private readonly string _dbConnection;
    
        public MyAppContextFactory()
        {
    
        }
        public MyAppContextFactory(string dbConnection)
            : this()
        {
            _dbConnection = dbConnection;
    
        }
    
        public MyAppContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<MyAppContext>();
            optionsBuilder.UseSqlServer(_dbConnection, opts => opts.CommandTimeout((int)TimeSpan.FromMinutes(15).TotalSeconds));
            return new MyAppContext(optionsBuilder.Options);
        }
    
    
    }
    

    我的连接字符串存在于appsettings的API层中。json&作为良好的实践,我不应该在API/UI层中添加任何对EF的引用。

    在这种分层架构中,如何根据环境设置连接字符串?

    谢谢

    1 回复  |  直到 7 年前
        1
  •  2
  •   Maxim Zabolotskikh    7 年前

    我认为EF实际上从2.0开始启动应用程序生成迁移。您需要将DesignTimeDbContextFactory添加到项目中,该项目将查询此用例的连接字符串,例如:

    public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<StorageContext>
        {
            public StorageContext CreateDbContext(string[] args)
            {
                IConfigurationRoot configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: false)
                    .AddJsonFile("appsettings.Development.json", optional: true)
                    .Build();
    
                var builder = new DbContextOptionsBuilder<StorageContext>();
                var connectionString = configuration.GetConnectionString("DefaultConnection");
                builder.UseSqlServer(connectionString);
    
                Console.WriteLine($"Running DesignTime DB context. ({connectionString})");
    
                return new StorageContext(builder.Options);
            }
        }