所以我没有启动文件,因为我的DAL在另一个项目中。我只是想能够读取该项目中的config.json文件以获取连接字符串。
我尝试实例化一个Configuration类(似乎在beta4中),并使用它来获取连接字符串,但它不断传回null值。有人有任何见解吗?
文件夹结构:
=>MyProject.DAL
BlogContext.cs
config.json
project.json
这是我的project.json
{
"version": "1.0.0-*",
"description": "MyProject.DAL Class Library",
"authors": [ "Admin" ],
"tags": [ "" ],
"projectUrl": "",
"licenseUrl": "",
"frameworks": {
"dnx451": { },
"dnxcore50": {
"dependencies": {
"Microsoft.CSharp": "4.0.1-beta-23409",
"System.Collections": "4.0.11-beta-23409",
"System.Linq": "4.0.1-beta-23409",
"System.Runtime": "4.0.21-beta-23409",
"System.Threading": "4.0.11-beta-23409"
}
}
},
"dependencies": {
"EntityFramework.Core": "7.0.0-beta8",
"EntityFramework.SqlServer": "7.0.0-beta8",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta8",
"Microsoft.Framework.Configuration.Abstractions": "1.0.0-beta8",
"Microsoft.Framework.Configuration.CommandLine": "1.0.0-beta8",
"Microsoft.Framework.Configuration.EnvironmentVariables": "1.0.0-beta8",
"Microsoft.Framework.Configuration.Json": "1.0.0-beta8",
"Microsoft.Framework.ConfigurationModel": "1.0.0-beta4",
"Microsoft.Framework.Logging.Console": "1.0.0-beta8",
"MyProject.Entities": "1.0.0-*"
}
}
这是config.json
{
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=.\\SQLEXPRESS;Database=SolutionPub;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
}
BlogContext.cs
public class BlogContext: DbContext
{
public BlogContext()
{
Database.EnsureCreated();
}
public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Image> Images { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var configuration = new Configuration();
var connectionString = configuration.Get("Data:DefaultConnection:ConnectionString");
optionsBuilder.UseSqlServer(connectionString);
base.OnConfiguring(optionsBuilder);
}
}
答案 0 :(得分:1)
系统不知道您要使用config.json
。你必须告诉它。
var configuration = new Configuration();
configuration.AddJsonFile("config.json");
var connectionString = configuration.Get("Data:DefaultConnection:ConnectionString");
如果它在另一个项目中,你首先应该问问自己为什么该项目直接访问配置文件而不是从启动项目传递它。但如果您真的想这样做,那么只需在AddJsonFile
调用中修改文件的路径。