.NET Core:我该如何设置连接字符串?

5
我将尝试使用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");
            }
        }
    }

1
你应该在 appsetting.json 中添加连接字符串设置。 - Nkosi
但是项目中没有 appsettings.json 文件。这就是为什么我放在 launchsettings.json 中的原因。那么我应该在哪里创建 appsettings.json 文件并与项目连接呢? - jorjj
3个回答

10

连接字符串设置应该在 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; }

}

您需要在 Startup 类的 ConfigureServices 方法中配置 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>();
    }
}

我在ConfigureService部分遇到了很多错误。即使我已经连接了客户端和服务器并拥有EF库,它仍然无法识别UserContext和Configuration。 - jorjj
当我添加您的UserContext构造函数时,我无法在访问层中使用此类,因为没有参数。 - jorjj
我所做的方式是为了使上下文能够与依赖注入一起使用。 - Nkosi
如果你有时间,可以看一下这个项目吗?我按照你的说法做了,但是它不起作用。这是项目链接:https://uploadfiles.io/ 。 - jorjj
请在Startup类的构造函数Startup(IHostingEnvironment environment)中考虑使用.SetBasePath(environment.ContentRootPath)。我的想法是使用环境的ContentRootPath属性而不是Directory.GetCurrentDirectory()。当前目录的工作方式类似于全局变量,可能会意外更改。 - oleksa
你希望本地开发人员能够在launchSettings中覆盖连接字符串或端口。"environmentVariables": {"ConnectionStrings.UserDatabase": "Server..."}比依赖应用程序设置更好。这样它总是指向dev、qa,并且开发人员可以在launch settings中进行覆盖。依靠开发人员记住撤消appsettings的更改并不是一个好主意。 - Nick Turner

4

我知道我有点晚了,但是如果您确实想在launchSettings.json中设置连接字符串,您可以创建一个名为ConnectionStrings:YourConnectionStringName的环境变量,然后它会被识别为连接字符串。

以您的具体示例为例:

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


0
您可以在 UserContext.cs 文件中进行更改。
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public UserContext CreateDbContext(string[] args)
        {
            IConfiguration configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json").Build();
            var builder = new DbContextOptionsBuilder<AppDbContext>();
            var connectionString = configuration.GetConnectionString("UserDatabase");
            builder.UseSqlServer(connectionString);
            return new AppDbContext(builder.Options);
        }
    }

而在文件 Startup.cs 中

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<UserContext>(options =>
               options.UseSqlServer(Configuration.GetConnectionString("UserDatabase"),
                   b => b.MigrationsAssembly("xxx.Data")));
    }

我为那些在一年后看到这样的代码的人感到遗憾。你需要重构代码,无论出于什么原因,将其移到代码的另一个位置或更改应用程序设置,否则这段代码就会崩溃。应用程序会停止运行数天,直到他们找出文件应该放置在哪里。 - Nick Turner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接