EF Core-连接字符串不能为空 [英] EF Core - Connection string cannot be null

查看:305
本文介绍了EF Core-连接字符串不能为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将ASP.Net Core 2.1EF Core 2.1

从PMC运行任何迁移时,出现以下错误

While running any Migration from PMC, I am getting the below error

值不能为null.参数名称:connectionString

Value cannot be null. Parameter name: connectionString

这是我的Context类的样子

This is how my Context class looks like

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的任何引用.

My Connection string is present in API layer in appsettings.json & as good practice I should not add any reference to EF in API/UI layer.

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

How do I set the connection string as per environment in such layered architecture?

谢谢.

推荐答案

EF实际上会启动您的应用程序以生成迁移.您需要将DesignTimeDbContextFactory添加到您的项目中,该项目将查询此用例的连接字符串,例如像这样:

EF actually starts your application to generate migration as of 2.0 I think. You need to add DesignTimeDbContextFactory to your project that will query the connection string for this use case, e.g. like this:

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);
        }
    }

这篇关于EF Core-连接字符串不能为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆