Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core .Net核心将连接字符串传递到DBContext类_Asp.net Core - Fatal编程技术网

Asp.net core .Net核心将连接字符串传递到DBContext类

Asp.net core .Net核心将连接字符串传递到DBContext类,asp.net-core,Asp.net Core,刚刚开始使用.NETCore,并面临将连接字符串信息传递到上下文控制台项目的问题 我有4个项目,使用.NETCore创建 MVC 服务层 域层 数据层 在MVC项目中,我有Startup.cs文件,在其中我正在读取appsettings.json文件 public void ConfigureServices(IServiceCollection services) { // Add framework services.

刚刚开始使用.NETCore,并面临将连接字符串信息传递到上下文控制台项目的问题

我有4个项目,使用.NETCore创建

  • MVC
  • 服务层
  • 域层
  • 数据层
  • 在MVC项目中,我有Startup.cs文件,在其中我正在读取appsettings.json文件

        public void ConfigureServices(IServiceCollection services)
            {
                // Add framework services.
                services.AddApplicationInsightsTelemetry(Configuration);
    
                services.AddMvc();
    
                // Add appsettings
                services.Configure<AppSettingsConfig>(Configuration.GetSection("AppSettings")); 
    }
    
    
    public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
    
            if (env.IsDevelopment())
            {
                // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
                builder.AddApplicationInsightsSettings(developerMode: true);
            }
            Configuration = builder.Build();
        }
    
    public void配置服务(IServiceCollection服务)
    {
    //添加框架服务。
    services.AddApplicationInsightsTelemetry(配置);
    services.AddMvc();
    //添加应用程序设置
    services.Configure(Configuration.GetSection(“AppSettings”);
    }
    公共启动(IHostingEnvironment环境)
    {
    var builder=new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile(“appsettings.json”,可选:true,重载更改:true)
    .AddJsonFile($“appsettings.{env.EnvironmentName}.json”,可选:true)
    .AddenEnvironmentVariables();
    if(env.IsDevelopment())
    {
    //这将使遥测数据更快地通过Application Insights管道,从而允许您立即查看结果。
    AddApplicationInsightsSettings(developerMode:true);
    }
    Configuration=builder.Build();
    }
    
    在我的第四个项目(数据层)中,它是一个控制台项目,具有以下DBContext类。此项目没有像i MVC项目那样具有Startup.cs。未在VS 2015默认情况下创建

    public class MyDWContext : DbContext
    {
        public MyDWContext() : base ()
        {
    
        }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
    
        }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {            
            optionsBuilder.UseSqlServer(@"Data Source=localhost;Initial Catalog=MyDW; Persist Security Info = False; User ID = TempUser; Password = Temp123");
        }
    
        public DbSet<User> Users { get; set; }
        public DbSet<Class> Classs { get; set; }
    }
    
    公共类MyDWContext:DbContext
    {
    公共MyDWContext():基()
    {
    }
    模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
    {
    基于模型创建(modelBuilder);
    }
    配置时受保护的覆盖无效(DBContextOptions Builder Options Builder)
    {            
    optionsBuilder.UseSqlServer(@“数据源=本地主机;初始目录=MyDW;持久安全信息=False;用户ID=TempUser;密码=Temp123”);
    }
    公共数据库集用户{get;set;}
    公共数据库集类{get;set;}
    }
    
    我也看过其他的帖子,但我相信它是用旧版本或RC版本创建的。因此,有时我无法找到正确的对象或.Net类

    由于连接字符串在MVC项目中,所以在MVC调用数据层期间,如何使用连接字符串


    我也有Web.API(Core)项目,它有自己的连接字符串(连接字符串中的不同用户配置,只有读取权限)。从Web2.API项目调用时,如何使用Web2.API连接字符串。

    与其将连接字符串传递给
    DbContext
    ,不如在
    Startup.cs
    中配置
    DbContext
    (如果可能的话)。有关如何配置
    DbContext
    并通过依赖项注入使用它的详细信息,请参阅official

    编辑:下面的代码不是好方法

    public static class ConnectionStringGetter
    {
        public static string ConStr{get;set;}
    }
    
    public Startup(IHostingEnvironment env)
    {
        //...
        Configuration = builder.Build();
        ConnectionStringGetter.ConStr =  Configuration.GetConnectionString("Default");
    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {            
        optionsBuilder.UseSqlServer(ConnectionStringGetter.ConStr);
    }
    
    但是,如果要将连接字符串传递给
    DbContext
    ,则可以使用

    下面是一个如何使用选项模式传递连接字符串的示例:

    首先,您需要一个可从数据层和MVC层访问的选项类

    public class ConnectionStringOption
    {
         public string ConStr { get ; set; }
    }
    
    然后设置选项值

    public void ConfigureServices(IServiceCollection services)
    {
         services.AddOptions();
         services.Configure<ConnectionStringOption>(options=>
         {
             // set connection string from configuration  
             options.ConStr = Configuration.GetConnectionString("Default");
         });      
    }
    
    最后
    DbContext

        private readonly IOptions<ConnectionStringOption> _conStrOptions;
    
        protected YourDbContext()
        {
        }
        public YourDbContext(IOptions<ConnectionStringOption> conStrOptions, DbContextOptions options) 
            : base(options)
        {
            _conStrOptions= conStrOptions;
        }
    
    ConfigureServices
    方法中

        public void ConfigureServices(IServiceCollection services)
        {
            // other stuff
            services.AddOptions();
            services.Configure<ConnectionStringOption>(options=>
            {
                // set connection string from configuration  
                options.ConStr = Configuration.GetConnectionString("Default");
            }); 
            DependencyResolver.ServiceProvider = services.BuildServiceProvider();
        }
    

    不介意第二种方式,它似乎不是有效的方式。感谢您的回复,但我可以在数据层的OnConfiguration函数中使用_conStrOptions属性吗
    protectedoverride void onconfigurang(DbContextOptionsBuilder optionsBuilder){}
    可以,但在这种情况下,您应该使用
    onconfigurang
    来配置
    DbContext
    ,而
    DbContext
    将取决于数据库(如SqlServer)提供程序。我认为这不是一个好的做法。\在接下来的通话中,选项为空。optionsBuilder.UseSqlServer(\u conStrOptions.Value.ConStr);您是否在
    Startup.cs
    中配置了
    DbContext
    ,例如:
    services.AddDbContext()
        public void ConfigureServices(IServiceCollection services)
        {
            // other stuff
            services.AddOptions();
            services.Configure<ConnectionStringOption>(options=>
            {
                // set connection string from configuration  
                options.ConStr = Configuration.GetConnectionString("Default");
            }); 
            DependencyResolver.ServiceProvider = services.BuildServiceProvider();
        }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {            
        var conStr = DependencyResolver.ServiceLocator.GetService<IOptions<ConnectionStringOption>>().Value.ConStr;
        optionsBuilder.UseSqlServer();
    }
    
    public static class ConnectionStringGetter
    {
        public static string ConStr{get;set;}
    }
    
    public Startup(IHostingEnvironment env)
    {
        //...
        Configuration = builder.Build();
        ConnectionStringGetter.ConStr =  Configuration.GetConnectionString("Default");
    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {            
        optionsBuilder.UseSqlServer(ConnectionStringGetter.ConStr);
    }