【问题标题】:There was an error running the selected code generator: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOption运行所选代码生成器时出错:无法解析类型“Microsoft.EntityFrameworkCore.DbContextOption”的服务
【发布时间】:2021-10-01 18:23:00
【问题描述】:

我正在使用 Visual Studio 2022 Preview 和 .NET 6 SDK。

在这里,我正在创建一个有 2 层的 webAPI 项目。 api 项目 (Bgvsystem.webAPI) 类库(BgvSystem.Persistance)

NuGet 包-

安装包 Microsoft.EntityFrameworkCore.SqlServer -Version 6.0.0-rc.1.21452.10

安装包 Microsoft.EntityFrameworkCore.Tools -Version 6.0.0-rc.1.21452.10

安装包 Microsoft.VisualStudio.Web.CodeGeneration.Design -版本 6.0.0-rc.1.21464.1

当我尝试使用脚手架添加控制器时,出现以下错误

There was an error running the selected code generator: unable to resolve service for type 'microsoft.entityframeworkcore.dbcontextoption.. While attempting to activate Dbcontext in  .net 6 and visual studio 2022 preview

如何解决这个问题?请帮忙。

【问题讨论】:

标签: asp.net-core-webapi .net-6.0 visual-studio-2022 entity-framework-6.4


【解决方案1】:

苦苦挣扎了3天,终于找到了错误并修复了。

实际上我必须将连接字符串放在 MyApp.Persistance.DbContextClass 中,如下所示

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Data Source=DESKTOP-SV8GPJ2\\SQLEXPRESS;Initial Catalog=StarterAppDB;Persist Security Info=True;User ID=sa;Password=Admin@1234");
            }
        }

然后它工作正常。

【讨论】:

    【解决方案2】:

    您需要将 DBContext 添加到 startup.cs 文件中的服务集合或作为构造函数 BGvSystemContext 类传递。

    【讨论】:

    • asp.net core 6上没有Startup.cs,只有Program.cs
    • @HeitorGiacomini 你可以添加它
    【解决方案3】:

    .NET 6

    你可以这样试试

    Program.cs

    builder.Services.AddDbContext<YourDbContext>(options =>
         options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
    

    appsettings.json

    "ConnectionStrings": {
       "DefaultConnection": "Server=YourServer; Database=YourDb; Integrated Security=true; MultipleActiveResultSets=true; Trusted_Connection=True"
    }
    

    YourDbContext.cs

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("Server=YourServer; Database=YourDb; Integrated Security=true; MultipleActiveResultSets=true; Trusted_Connection=True");
        }
    }
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2020-08-10
    • 2019-10-15
    • 2022-01-24
    • 2016-05-13
    • 1970-01-01
    • 2020-06-24
    • 2014-01-13
    • 1970-01-01
    相关资源
    最近更新 更多