大家好我无法将数据保存到数据库。我正在使用EF
和.net core
。我在下面提供了我的示例代码:
这里究竟出了什么问题?我在services.AddDbContext
中为MyContext提供了ConfigureServices
。
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
{
"Data": {
"ConnectionString": "Data Source=MyDataSource;Initial Catalog=MyCatalog;Trusted_Connection=True"},
另一类:
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
}
}
}
答案 0 :(得分:0)
查看以下内容:Value cannot be null. Parameter name: connectionString appsettings.json in starter
我认为您的appsettings.json应该如下所示:
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=MyDataSource;Initial Catalog=MyCatalog;Trusted_Connection=True"
}
}
跳过“数据”部分。