我有一个问题。我有一个类如下:我无法将数据保存到我的数据库。
public class SomeClassContext : DbContext
{
private IConfigurationRoot _configurationRoot;
public SomeClassContext(DbContextOptions<SomeClassContext> contextOptions, IConfigurationRoot configurationRoot)
{
this._configurationRoot = configurationRoot;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_configurationRoot["Data:ConnectionString"]);
}
我的appsettings.json
{
"Data": {
"ConnectionString": "Data Source=MyDataSource;Initial Catalog=MyCatalog",
}
当我尝试实例化SomeClassContext并为构造函数提供参数时,我得到空值
public class MyClass
{
private SomeClassContext context;
private string _categoryName;
private Func<string, LogLevel, bool> _filter;
public MyClass(string categoryName, Func<string, LogLevel, bool> filter)
{
_categoryName = categoryName;
_filter = filter;
context = new SomeClassContext(//parameters here are required. What should be my parameters here that will not result to null)
}
public void SomeMethod()
{
var obj = new MyEntity()
{
//assume I have initialize object here
};
try
{
context.MyEntity.Add(obj);
context.SaveChanges();
}
catch(Exception e)
{
//debugger throws here
//cannot save to DB
}
}
}