【问题标题】:error when giving migration update and remove. but does the add work?提供迁移更新和删除时出错。但是添加有效吗?
【发布时间】:2022-11-19 05:37:37
【问题描述】:

我正在一个关于 .NET 6 的 udemy 课程中做一个项目。无论如何,我想到的是,当我运行项目“迁移添加”时,一切都很顺利。但是在执行remove或者database-update的时候,出现如下异常。 System.InvalidOperationException: The ConnectionString property has not been initialized.

好吧,没有一个工作。我将离开 GitHub 和一些项目代码以备不时之需。我还将使用 --verbose 保留迁移命令。 Project on GitHub。 另一个细节是我在同一个提交中下载了教授的项目,并且他的命令有效。我使用比较站点检查了所有内容,项目是相同的。我还使用相同版本的依赖项进行了测试,但也没有。

CLI 使用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"
          }
        }
    }

程序.cs

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

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSqlServer<ApplicationDbContext>(builder.Configuration["Database: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();

我已经更新了所有项目依赖项并遵循了我在此处找到的一些解决方案,如 this 和文档中的其他解决方案,如 this

【问题讨论】:

    标签: c# asp.net entity-framework


    【解决方案1】:

    我检查了你的github 而你正在这样做

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

    但是你的连接字符串实际上有不同的路径

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

    您应该将 ConnectionString:IWantDb 更改为 Database:IWantDb

    【讨论】:

    • 我按照我说的做了,让 json 与 program.cs 中的相同,但错误仍然存​​在。奇怪的是构建工作正常,错误稍后出现。
    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 2019-12-16
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多