[英]Value cannot be null. Parameter name connectionString
Hi guys I'm having trouble saving my data to DB. 嗨,大家好,我无法将数据保存到数据库。 I'm using
EF
and .net core
. 我正在使用
EF
和.net core
。 I have provide my sample code below: 我在下面提供了示例代码:
What's actually wrong here? 这里到底有什么问题? I provided
services.AddDbContext
in ConfigureServices
for MyContext. 我公司提供
services.AddDbContext
在ConfigureServices
为MyContext。
public class MyContext: DbContext
{
private IConfigurationRoot _config;
public MyContext(IConfigurationRoot config)
{
this._config = config;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_config["Data:ConnectionString"]);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
}
}
appsettings.json appsettings.json
{
"Data": {
"ConnectionString": "Data Source=MyDataSource;Initial Catalog=MyCatalog;Trusted_Connection=True"},
Another Class: 另一类:
public class AnotherClass
{
private MyContext mycontext;
private IConfigurationRoot configurationRoot;
public AnotherClass()
{
var builder = new ConfigurationBuilder();
configurationRoot = builder.Build();
mycontext = new MyContext(configurationRoot);
}
public MyMethod()
{
try
{
//object to be saved using EF
var saveObj = new SaveObj()
{
//pretend to have initialize some object here to save
};
mycontext.SaveObj.Add(saveObj);
mycontext.SaveChanges();
}
catch(Exception e)
{
//Throws an exception. Value cannot be null. Parameter name: connectionString
}
}
}
Check this out: Value cannot be null. 签出: 值不能为null。 Parameter name: connectionString appsettings.json in starter
参数名称:starter中的connectionString appsettings.json
I think your appsettings.json should look like this: 我认为您的appsettings.json应该看起来像这样:
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=MyDataSource;Initial Catalog=MyCatalog;Trusted_Connection=True"
}
}
Skip the "Data" part. 跳过“数据”部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.