实体框架脚手架和迁移不起作用

Posted

技术标签:

【中文标题】实体框架脚手架和迁移不起作用【英文标题】:Entity Framework scaffold and migration not working 【发布时间】:2021-12-09 20:12:46 【问题描述】:

我在 asp.net webapi 项目中使用具有 1 个代码优先 DbContext 和 1 个数据库优先 DbContext 的项目。 运行以下命令来更新 db/context 会导致以下错误:


dotnet ef dbcontext scaffold Name=ConnectionStrings:Cloud Microsoft.EntityFrameworkCore.SqlServer

System.InvalidOperationException: A named connection string was used, but the name 'ConnectionStrings:Cloud' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See
 https://go.microsoft.com/fwlink/?linkid=850912 for more information.
   at Microsoft.EntityFrameworkCore.Storage.Internal.NamedConnectionStringResolverBase.ResolveConnectionString(String connectionString)
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineerScaffolder.ScaffoldModel(String connectionString, DatabaseModelFactoryOptions databaseOptions, ModelReverseEngineerOptions modelOptions, ModelCodeGenerationOptions codeOptions)
   at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String outputContextDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, String modelNamespace, String contextNamespace, Boolean useDataAnnotati
ons, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluralize)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, String modelNamespace, String contextNamespace, Boolean useData
Annotations, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluarlize)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>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)

dotnet ef 迁移添加 test -c AdminContext

System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts
 a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
   at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>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)

这是我的代码

   public static class Program 
       public static void Main(string[] args) 
           Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>  webBuilder.UseStartup<Startup>(); ).Build().Run();
       
   
   public class Startup 
       public Startup(IConfiguration configuration) 
           Configuration = configuration;
       

       private IConfiguration Configuration  get; 

       // This method gets called by the runtime. Use this method to add services to the container.
       public void ConfigureServices(IServiceCollection services) 
           services.AddDbContext<AdminContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Admin")));
           services.AddDbContext<CloudContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Cloud")));
           services.AddControllers();
       

       public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
           app.UseHsts();
           app.UseHttpsRedirection();
           app.UseRouting();
           app.UseAuthorization();
           app.UseEndpoints(endpoints =>  endpoints.MapControllers(); );
       
   
    public class AdminContext : DbContext 
        public AdminContext()  
        public AdminContext(DbContextOptions<AdminContext> options) : base(options)  
        
        public DbSet<User> Users  get; set; 
    

我实际上是在做异常要我做的事情?谁能告诉我如何解决这个问题? 应用程序本身运行良好,并正确使用带有连接字符串的 appsettings/user-secrets。 我正在使用 dotnet 5.0.402 和 ef 5.0.11

【问题讨论】:

conf 是否来自 JSON 文件? @AndriyShevchenko appsettings.json 用于生产构建,用户机密用于开发构建 【参考方案1】:

我猜你的配置(appsettings.json/usersecrets)格式不正确,应该是这样的:


  "ConnectionStrings": 
    "Admin": "***",
    "Cloud": "***"
  ,
  ...

还可以尝试从上下文中删除空构造函数(可能会导致使用而不是使用 DbContextOptions 的构造函数)

【讨论】:

【参考方案2】:

将我的 Program.cs 更改为

    public static class Program 
        public static void Main(string[] args) => CreateHostBuilder(args).Build().Run();

        // EF Core uses this method at design time to access the DbContext
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
    

修复了问题

【讨论】:

以上是关于实体框架脚手架和迁移不起作用的主要内容,如果未能解决你的问题,请参考以下文章

VS 2010 - 带有 MySql 存储过程的实体框架似乎不起作用

具有接口的实体框架不起作用 - 处理相同的最佳方法是啥?

在实体框架 6 中不起作用的实体之间的一对一关系

ASP.NET MVC Core 和实体框架中的 ToListAsync 不起作用

iOS 10 本地通知不起作用(迁移到 UserNotifications 框架)

实体框架:部分更新记录不起作用