【问题标题】:.NET Core: How can I set the connection string?.NET Core:如何设置连接字符串?
【发布时间】:2019-01-07 08:46:51
【问题描述】:

我正在尝试使用 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 中添加连接字符串设置
  • 但是项目中没有 appsettings.json 文件。这就是我放入launchsettings.json 的原因。那么在哪里可以创建 appsettings.json 文件并连接到项目呢?

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


【解决方案1】:

连接字符串设置应该在 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 方法中的Startupclass 中配置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 和配置。
  • 当我添加你的UserContext构造函数时,我不能在访问层使用这个类,因为没有参数
  • 我这样做的方式是让上下文可以与依赖注入一起使用。
  • 有时间可以看看项目吗?我按照你说的做了,但是没有用。这是项目:uploadfiles.io
  • 请考虑在 Startup 类构造函数Startup(IHostingEnvironment environment) 中使用.SetBasePath(environment.ContentRootPath)。我的想法是使用环境ContentRootPath 属性而不是Directory.GetCurrentDirectory()。当前目录就像一个全局变量,可能会被意外更改。
【解决方案2】:

您可以在文件 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")));
    }

【讨论】:

  • 我为工作一年后看到这样代码的人感到难过。无论出于何种原因,您都需要将代码重构到另一个位置或更改您的应用程序设置,并且此代码会蓬勃发展。应用程序关闭了好几天,直到他们确定文件的位置。
猜你喜欢
  • 2020-04-14
  • 2016-10-02
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 2019-04-21
  • 1970-01-01
  • 2017-05-06
相关资源
最近更新 更多