0

I have a class library for a Repository to handle the Database operation, and I tried to create DbContext and set ConnectionString as well, but it did not work.

    namespace CoreCrud.Repository
    {
        public class CoreCrudDBContext: DbContext
        {
            private readonly IConfiguration _configuration;
            public CoreCrudDBContext(DbContextOptions<CoreCrudDBContext> options, IConfiguration configuration) : base(options)
            {
                _configuration = configuration;
            }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                String connString = _configuration.GetConnectionString("CoreCrudDatabase");
                Console.WriteLine(connString);
    
                if (!optionsBuilder.IsConfigured)
                    optionsBuilder.UseMySQL(connString);
            }
    
            public DbSet<Person> person { get; set; }
        }
    }

I also have appsettings.json:


    {
      "ConnectionStrings": {
        "CoreCrudDatabase": "server=localhost;database=core_crud;user=root;password=password"
      }
    }

And the DbContext is defined in Startup.cs in web mvc project as follows:


    public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllersWithViews();
                services.AddDbContext<CoreCrudDBContext>();
            }

But each time the project runs it gives this error: optionsBuilder.UseMySQL(connString); inside OnConfiguring method.

System.ArgumentNullException: 'Value cannot be null. (Parameter 'connectionString')'

pl-jay
  • 970
  • 1
  • 16
  • 33
  • 1
    Have you confirmed that your app startup adds that file to the configuration? If this is the first thing you’ve put in that JSON file then it’s an easy thing to miss. – Scott Hannen Oct 16 '20 at 20:25
  • @ScottHannen yes repository class library is added as dependency to web mvc project and the dbcontext also added to startup for di. – pl-jay Oct 17 '20 at 04:56
  • But in your startup, do you specify that `IConfiguration` should include that file? `.AddJsonFile("somefile.json")`Not doing that can produce the result you're seeing. It's in the file, but that file isn't being used. – Scott Hannen Oct 17 '20 at 13:21
  • @ScottHannen you mean startup on web mvc project right? – pl-jay Oct 17 '20 at 13:27
  • Yes, Check this: https://stackoverflow.com/questions/49046847/how-can-i-add-a-custom-json-file-into-iconfiguration – Scott Hannen Oct 17 '20 at 13:30
  • @ScottHannen ok, thanks i'll look into it. – pl-jay Oct 17 '20 at 13:35

0 Answers0