【发布时间】:2018-10-05 23:35:11
【问题描述】:
我对位于 json 配置文件中的连接字符串有疑问, 像往常一样:
- 我创建了一个类:applicationDbcontext
- 我创建了一个 DbSet {get;set;}
- 将其集成到控制器中
- 将其添加到服务中
我已阅读并尝试了相关问题中插入的所有建议: asp.net core 2.0 - Value cannot be null. Parameter name: connectionString 但他们都不适合我 这是我的实现, 希望有人能帮帮我,谢谢
A_ 数据库上下文:
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
Database.EnsureCreated();
}
public DbSet<Person> Persons { get; set; }
}
}
B_应用设置:config.json和config.development.json
{
"ConnectionString": {
"testConnection": "Server=(localdb)\\mssqllocaldb;Database=mvc_db;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
C_服务注入
启动:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.Json")
.AddJsonFile("appsettings.Development.Json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
配置服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("testConnection"));
});
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
D_注入控制器:
private readonly ApplicationDbContext _db;
public PersonController(ApplicationDbContext db)
{
_db = db;
}
IEnumerable<Person> People { get; set; }
public IActionResult Index()
{
People = _db.Persons.ToList();
return View(People);
}
我尝试将整个 connectionString 插入到 configuration.GetConnectionString("Here"); 并将连接字符串的位置从上更改为下,反之亦然。 但是没有什么能解决 connectionString 的返回空值问题。 任何帮助请感谢
【问题讨论】:
-
提供的默认设置包括在 ApplicationDBContext 构造函数中声明参数时的类型 public ApplicationDbContext(DbContextOptions
options) : base(options) { } 不确定它会改变多少,但有些东西我注意到这是不同的
标签: c# asp.net-core entity-framework-6 asp.net-core-mvc entity-framework-core