c# - 在 Blazor .net core 应用程序中查找连接字符串时出错

标签 c# asp.net-core .net-core entity-framework-core blazor

我有一个带有 EF Core 5 的 .netcore 3.1 blazor 应用程序,并在使用以下命令搭建我的数据库之后 Scaffold-DbContext "Name=MyDb" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyDb_Context -Force

如果我使用,一切正常 Scaffold-DbContext "Server=servername;Database=MyDb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyDb_Context -Force 但我想避免在源代码中包含连接字符串。

一切都正确,但是,当我尝试将数据显示到列表时,出现此错误: System.InvalidOperationException: A named connection string was used, but the name 'MyDb' 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.

下面是我的 appsettings.json 的代码:

{
"ConnectionStrings": {
    "MyDb": "Server=servername;Database=MyDb;Integrated Security=True"
  }
}

这是我的 MyDb_Context:

    public partial class MyDb_Context : DbContext
    {
        public MyDb_Context()
        {
        }

        public MyDb_Context(DbContextOptions<MyDb_Context> options)
            : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Name=MyDb");
            }
        }
...
}

这是我的 Startup.cs:

    public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            Configuration = configuration;
            _env = env;
        }

        private readonly IWebHostEnvironment _env;
        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            var connection = Configuration.GetConnectionString("MyDb");
            services.AddDbContext<MyDb_Context>(options => options.UseSqlServer(connection));
        }
...
}

这是我的服务中所调用的内容:

 public class MyDbService
    {
        public readonly MyDb_Context mydb_context;

        public MyDbService(MyDb_Context mydbctx)
        {
            MyDb_Context = mydbctx;
            MyDb_Context.Database.SetCommandTimeout(60);
        }

        public Task<List<MyDbTableName>> GetMyDbContent()
        {
            var usernames = mydb_context.usernames.Where(u => u.AppId == 2).ToListAsync();

            return usernames ;
        }
...
}

然后在我的 Razor 页面中使用以下代码:

@code{
       private List<usernames> _usernames;

       
       MyDbService mydbservice = new MyDbService(new MyDb_Context()); //I think this line is where it is breaking

       protected override async Task OnInitializedAsync()
        {
            //Grab function from the service listed above
            //Function:
            _usernames = await mydbservice.GetMyDbContent();
        }

}

我不知道为什么它找不到连接字符串,我什至可以在startup.cs上放置一个断点 optionsBuilder.UseSqlServer("Name=MyDb");并且它能够完美地读取连接字符串。

我还可以看到 DBContext 在尝试时被加载 services.toList();并在其上设置断点。

请帮忙,我已经这样做一个多星期了,已经耗尽了我的努力。

最佳答案

  • Startup类中注册服务MyDbService,稍后由DI注入(inject):
public void ConfigureServices(IServiceCollection services)
        {
            //...other services            
            services.AddScoped<MyDbService>();
        }
  • 将服务注入(inject)组件
@* inject the service *@
@inject MyDbService mydbservice
 
//....

@code{
    private List<usernames> _usernames;

//DO NOT instianate the service, it's injected 
   // MyDbService mydbservice = new MyDbService(new MyDb_Context()); //I think this line is where it is breaking

    protected override async Task OnInitializedAsync()
    {
        //Grab function from the service listed above
        //Function:
        _usernames = await mydbservice.GetMyDbContent(); //now it's working
    }
}

  • 修改 MyDbService 构造函数中的下一行:
  // MyDb_Context = mydbctx; //invalid
  mydb_context = mydbctx;

使用命名连接的 Scaffold-DbContext 是有效的,因为我们使用的是 DI。

Scaffold-DbContext "Name=MyDb" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyDb_Context -Force

我测试了这个解决方案,它工作正常。

关于c# - 在 Blazor .net core 应用程序中查找连接字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65832644/

相关文章:

sql-server - 我无法使用 Entity Framework Core 更新数据库

c# - 在 .NET Core API 应用程序中使用 FluentScheduler 期间的 DependencyInjection 问题

c# - 如何从 .net 核心客户端生成 JWT Bearer Flow OAuth 访问 token ?

c# - 为什么 aforge.net 无法检测所有网络摄像头分辨率

c# - 在类型 'Template' 中找不到属性 'FrameworkElement'

c# - 从网络爬虫中提取内容时,哪些解决方案更快

将 DataRow 转换为 T 类型时,C# Int64Converter 无法从 System.Int64 错误转换

c# - EF 核心自引用

c# - ASP.NET Core 托管和服务器端 Blazor 之间到底有什么区别?

c# - 静音 dotnet cli 输出中的所有警告