gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:22 24 4
gpt4 key购买 nike

我正在尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com