0

Hi guys I'm having trouble saving my data to DB. I'm using EF and .net core. I have provide my sample code below:

What's actually wrong here? I provided services.AddDbContext in ConfigureServices for 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

{
  "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
        }
    }
}

1 Answers1

1

Check this out: Value cannot be null. Parameter name: connectionString appsettings.json in starter

I think your appsettings.json should look like this:

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=MyDataSource;Initial Catalog=MyCatalog;Trusted_Connection=True"
  }
}

Skip the "Data" part.

LuvForAirplanes
  • 761
  • 8
  • 23