c# - .NET 核心 : How can I set the connection string?

标签 c# asp.net-core connection-string

我正在尝试使用 Blazor 的 CRUD 函数并按照一些文章来执行此操作。在文章中,有一部分我应该将我的连接放在上下文文件中,但它没有说明如何设置连接字符串。

我将此代码行放在 launchSettings.json 中:

{
  "ConnectionStrings": {
    "UserDatabase": "Server=DESKTOP-2K2A6GN;Database=Assignment4;Trusted_Connection=True;"
  },
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:56244/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Assignment4.Server": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:56248/"
    }
  }
}

我尝试将连接字符串添加到上下文文件中,但没有成功。

public class UserContext : DbContext
    {
        public virtual DbSet<User> tblUser { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(@"UserDatabase");
            }
        }
    }

最佳答案

连接字符串设置应该在 appsetting.json 文件中。将文件添加到项目中

appsetting.json

{
  "ConnectionStrings": {
    "UserDatabase": "Server=DESKTOP-2K2A6GN;Database=Assignment4;Trusted_Connection=True;"
  }
}

更新 DbContext 以便对其进行配置。

public class UserContext : DbContext {

    public UserContext(DbContextOptions<UserContext> options): base(options) {

    }

    public virtual DbSet<User> tblUser { get; set; }

}

您可以在 ConfigureServices 方法的 Startup 类中配置 DbContext。

public class Startup {

    public Startup(IHostingEnvironment env) {

        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
    }

    static IConfiguration Configuration { get; set; }

    public void ConfigureServices(IServiceCollection services) {    

        services.AddDbContext<UserContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("UserDatabase"));
        );

        //...
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        }

        app.UseBlazor<Client.Program>();
    }
}

关于c# - .NET 核心 : How can I set the connection string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51605177/

相关文章:

java - 像 C#/Java 这样的高级语言屏蔽移位计数操作数的原因是什么?

r - 访问通过 file() 创建的文件连接的属性

c# - 如何使用其他构造函数的参数在类中检索 HubContext (SignalR)?

c# - 由于类型不匹配,无法完成日期时间转换

asp.net-core - 如何启动自托管 WebListener Web 端点?

c# - InvalidOperationException : Cannot resolve scoped service 'Microsoft. AspNetCore.Identity.UserManager .NET 核心 2.0

C# - 如何安全地存储 MySQL 连接字符串以便没有人可以看到它?

entity-framework - Entity Framework 6 以编程方式连接到 Postgres

c# - C++ 和 C# 数组和 Void 转换

asp.net-mvc - ASP.NET MVC 删除方法将 Id/model 传递给 Controller