Search code examples
.net-6.0

an-item-with-the-same-key-has-already-been-added .net6 issue on adddbcontext


I converted my .netcore3.1 project to .net6 because .netcore3.1 is deprecated now I can see below error after adding microsoft entityframework in .net 6

"An item with the same key has already been added. Key: server=""id="";password="";database="";convertzerodatetime=True;defaultcommandtimeout=120"

This error occured because addDbcontext added keys(connectionstring) multiple times


Solution

  • This will be helpfull for people who want to convert .netcore3.1 to .net6 I used below code in Context File

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
      
    
          {
                if (!optionsBuilder.IsConfigured)
                {
                    optionsBuilder.UseMySQL("");//add your connectionstring here
                }
        }
    

    As well as i added this fix in startup.cs file this will allow only once to add adddbcontext

            bool isconfig = false;
            services.AddDbContext<GuardiansContext>(opts =>
            {
                if (!isconfig)
                {
                    isconfig = true;
                    opts.UseMySQL(sp.GetRequiredService<IConfigurationClient().GetConfigurationValue("").Result).EnableSensitiveDataLogging();
                }
            });
    

    Thanks, Ashwinikumar