【问题标题】:EF Core - Connection string cannot be nullEF Core - 连接字符串不能为空
【发布时间】:2019-05-13 17:26:05
【问题描述】:

我正在使用ASP.Net Core 2.1 和EF Core 2.1

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

值不能为空。参数名称:连接字符串

这就是我的 Context 类的样子

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.json 的 API 层中,作为一种好的做法,我不应该在 API/UI 层中添加对 EF 的任何引用。

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

谢谢。

【问题讨论】:

    标签: c# entity-framework-core asp.net-core-2.1 ef-core-2.1


    【解决方案1】:

    我认为 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);
            }
        }
    

    【讨论】:

    • 就像我尝试使用您的 sn-p 一样,但收到错误“ConfigurationBuilder”不包含“SetBasePath”的定义,并且没有可访问的扩展方法“SetBasePath”接受第一个参数类型“可以找到 ConfigurationBuilder'(您是否缺少 using 指令或程序集引用?)
    • 这来自Microsoft.Extensions.Configuration 或Microsoft.Extensions.Configuration.FileExtensions,不确定到底是哪一个。基本上,您可以将我的实现更改为最适合您的方式,其想法是将连接注入 DbContext 以生成迁移。您从哪里阅读它以及如何阅读取决于您。
    猜你喜欢
    • 2020-04-14
    • 2021-07-26
    • 2018-09-24
    • 2018-02-11
    • 2018-05-28
    • 2019-06-26
    • 2021-01-29
    • 1970-01-01
    相关资源
    最近更新 更多