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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.