DbContext OnConfiguring(optionsBuilder) has optionsBuilder.IsConfigured == false although private member of class Program builds options....

Juan Dent 236 Reputation points
2022-08-24T21:59:29.277+00:00

The call to DbContext.OnConfiguring receives an instance of DbContextOptionsBuilder called optionsBuilder which has its property IsConfigured equal to false...
It should be equal to true since in the Program class we set the optionsBuilder to UseSqlite like so:

    internal class Program  
    {  
        private static IConfigurationRoot _configuration;  
        private static DbContextOptionsBuilder<SeguroMedicoMFCContext> _optionsBuilder;  
        static void Main(string[] args)  
        {  
            BuildConfiguration();  
            BuildOptions();  
  
            Run();  
        }  
        static void BuildConfiguration()  
        {  
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json",  
                optional: true, reloadOnChange: true);  
            _configuration = builder.Build();  
        }  
  
        static void BuildOptions()  
        {  
            _optionsBuilder = new DbContextOptionsBuilder<SeguroMedicoMFCContext>();  
            _optionsBuilder.UseSqlite(_configuration.GetConnectionString("SeguroMedicoMFC"));  
            bool configured = _optionsBuilder.IsConfigured;  
  
        }  
  
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
696 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,205 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,031 Reputation points
    2022-08-24T23:01:36.223+00:00

    Try my NuGet package ConfigurationLibrary created in .NET Core 5, works with .NET Core 6. Why three environments, because it's good practice, for you just use the one.

    {  
      "ConnectionsConfiguration": {  
        "ActiveEnvironment": "Development",  
        "Development": "Data Source=q:\\data\\SeguroMedicoMFC.sqlite;",  
        "Stage": "Stage connection string goes here",  
        "Production": "Prod connection string goes here"  
      }  
    }  
    

    Then in the DbContext, add a using statement using ConfigurationLibrary.Classes;

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    {  
    	if (!optionsBuilder.IsConfigured)  
    	{  
    		optionsBuilder.UseSqlite(ConfigurationHelper.ConnectionString());  
    	}  
    }  
      
    

    Place an appsettings.json file in the root folder of the project, set copy if newer.

    0 comments No comments

0 additional answers

Sort by: Most helpful