Home > Back-end >  error when giving migration update and remove. but does the add work?
error when giving migration update and remove. but does the add work?

Time:11-19

I'm doing a project in an udemy course about .NET 6. Anyway, what occurs to me is that when I run the project "migration add" everything goes perfectly. However, when executing remove or database-update, the following exception appears. System.InvalidOperationException: The ConnectionString property has not been initialized.

Well none worked. I'll be leaving GitHub and some project code in case it helps. I will also leave the migration command using --verbose. Project on GitHub. Another detail is that I downloaded the professor's project in the same commit, and his commands work. I checked everything using a comparison site and the project is the same. I also tested using the same versions of the dependencies, but nothing too.

CLI using dotnet ef migrations remove --verbose

 EST\IWantApp\src" --verbose
    Using assembly 'IWantApp'.
    Using startup assembly 'IWantApp'.
    Using application base 'C:\Users\VOTOGAMES\OneDrive\Documentos\workspace\ws curso csharp API REST\IWantApp\src\bin\Debug\net6.0'.
    Using working directory 'C:\Users\VOTOGAMES\OneDrive\Documentos\workspace\ws curso csharp API REST\IWantApp\src'.
    Using root namespace 'IWantApp'.
    Using project directory 'C:\Users\VOTOGAMES\OneDrive\Documentos\workspace\ws curso csharp API REST\IWantApp\src\'.
    Remaining arguments: .
    Finding DbContext classes...
    Finding IDesignTimeDbContextFactory implementations...
    Finding application service provider in assembly 'IWantApp'...
    Finding Microsoft.Extensions.Hosting service provider...
    Using environment 'Development'.
    Using application service provider from Microsoft.Extensions.Hosting.
    Found DbContext 'ApplicationDbContext'.
    Finding DbContext classes in the project...
    Using context 'ApplicationDbContext'.
    Finding design-time services referenced by assembly 'IWantApp'...
    Finding design-time services referenced by assembly 'IWantApp'...
    No referenced design-time services were found.
    Finding design-time services for provider 'Microsoft.EntityFrameworkCore.SqlServer'...
    Using design-time services from provider 'Microsoft.EntityFrameworkCore.SqlServer'.
    Finding IDesignTimeServices implementations in assembly 'IWantApp'...
    No design-time services were found.
    System.InvalidOperationException: The ConnectionString property has not been initialized.
       at Microsoft.Data.SqlClient.SqlConnection.PermissionDemand()
       at Microsoft.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
       at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
       at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
       at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
       at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
       at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
       at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
       at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
       at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
       at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext _, TState s)
       at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
       at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
       at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists)
       at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists()
       at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
       at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.GetAppliedMigrations()
       at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.RemoveMigration(String projectDir, String rootNamespace, Boolean force, String language)
       at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.RemoveMigration(String contextType, Boolean force)
       at Microsoft.EntityFrameworkCore.Design.OperationExecutor.RemoveMigrationImpl(String contextType, Boolean force)
       at Microsoft.EntityFrameworkCore.Design.OperationExecutor.RemoveMigration.<>c__DisplayClass0_0.<.ctor>b__0()
       at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
       at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
    The ConnectionString property has not been initialized.

ApplicationDbContext

using IWantApp.Domain.Products;
    using Microsoft.EntityFrameworkCore;
    
    namespace IWantApp.Infra.Data;
    
    public class ApplicationDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<Category> Categories { get; set; }
    
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) 
        { 
    
        }
    
        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<Product>()
                .Property(p => p.Name).IsRequired();
            builder.Entity<Product>()
                .Property(p => p.Description).HasMaxLength(255);
            builder.Entity<Category>()
                .Property(c => c.Name).IsRequired();
        }
    
        protected override void ConfigureConventions(ModelConfigurationBuilder configuration)
        {
            configuration.Properties<string>()
                .HaveMaxLength(100);
        }
    
    
    }


appsettings.Development.json

{
      
        "Database": {
          "IWantDb": "Server=localhost;Database=IWantDb;User Id=sa;Password=123456;MultipleActiveResultSets=true;Encrypt=YES;TrustServerCertificate=YES"
        },
    
        "Logging": {
          "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
          }
        }
    }

Program.cs

using IWantApp.Endpoints.Categories;
using IWantApp.Infra.Data;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSqlServer<ApplicationDbContext>(builder.Configuration["ConnectionString:IWantDb"]);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapMethods(CategoryPost.Template, CategoryPost.Methods, CategoryPost.Handle);
app.MapMethods(CategoryGetAll.Template, CategoryGetAll.Methods, CategoryGetAll.Handle);
app.MapMethods(CategoryPut.Template, CategoryPut.Methods, CategoryPut.Handle);

app.Run();

I've already updated all project dependencies and followed some solutions I found here like this and other solutions in the documentation like this.

CodePudding user response:

I've checked your github And you're doing this

builder.Services.AddSqlServer<ApplicationDbContext>(builder.Configuration["ConnectionString:IWantDb"]);

But your connection string actually has different path

"Database": {
          "IWantDb": "Server=localhost;Database=IWantDb;User Id=sa;Password=123456;MultipleActiveResultSets=true;Encrypt=YES;TrustServerCertificate=YES"
            },

You should change ConnectionString:IWantDb to Database:IWantDb

  • Related