2017-01-07 62 views
2

信息
我的解決方案中有多個項目,其中一個是DAL,另一個是ASP.NET MVC6項目。 由於MVC6項目也是啓動項目,我需要在那裏添加我的連接字符串。我看到this solution,但它不被接受,也沒有工作。使用多個連接字符串

我嘗試
appsettings.json

"Data": { 
    "DefaultConnection": { 
    "ConnectionString": "Server=.\\SQLEXPRESS;Database=Bar;Trusted_Connection=True;MultipleActiveResultSets=true" 
    }, 
    "FooBar": { 
    "ConnectionString": "Server=.\\SQLEXPRESS;Database=Bar;Trusted_Connection=True;MultipleActiveResultSets=true" 
    } 
} 

Startup.cs

public void ConfigureServices(IServiceCollection services) 
{ 
    // Add framework services. 
    services.AddEntityFramework() 
     .AddSqlServer() 
     .AddDbContext<ApplicationDbContext>(options => 
      options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])) 
      .AddDbContext<ApplicationDbContext>(options => 
      options.UseSqlServer(Configuration["Data:FooBar:ConnectionString"])); 
} 

然而,當我嘗試訪問使用FooBar連接字符串我得到的數據以下信息:

「附加信息:在應用程序配置文件中找不到名爲'FooBar'的連接字符串可能爲 。」

問題
我如何多連接字符串的工作?

回答

4

如果你把在asp.net核心看看official documentation for connection strings的例子顯示了存儲在appsettings.json這樣

{ 
    "ConnectionStrings": { 
    "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;" 
    }, 
} 

哪個連接字符串,當適用於您的示例將成爲。

{ 
    "ConnectionStrings": { 
    "DefaultConnection": "Server=.\\SQLEXPRESS;Database=Bar;Trusted_Connection=True;MultipleActiveResultSets=true", 
    "FooBar": "Server=.\\SQLEXPRESS;Database=Bar;Trusted_Connection=True;MultipleActiveResultSets=true" 
    } 
} 

配置在Startup.cs與配置字符串的上下文從配置被讀取將使用GetConnectionString()方法與配置密鑰

public void ConfigureServices(IServiceCollection services) { 
    // Add framework services. 
    services 
     .AddEntityFramework() 
     .AddSqlServer() 
     .AddDbContext<ApplicationDbContext>(options => 
      options.UseSqlServer(Configuration.GetConnextionString("DefaultConnection")) 
     .AddDbContext<ApplicationDbContext>(options => 
      options.UseSqlServer(Configuration.GetConnextionString("FooBar")); 
} 

現在一個觀察到的問題與上述情況下如何在原始配置問題是現在有兩個連接字符串用於相同的上下文。

嘗試使用多個連接字符串來處理相同的上下文會導致問題,因爲框架在請求上下文時不知道使用哪個選項。

+0

第二部分不起作用。 我在'Configuration.GetConnectionString'上得到一個錯誤:'IConfigurationRoot'沒有包含'GetConnectionString'的定義,也沒有找到接受類型'IConfigurationRoot'的第一個參數的擴展方法'GetConnectionString'(你是否缺少一個using指令還是程序集引用?) – Hypenate

+0

您使用的是什麼版本的asp.net。檢查以確保你沒有省略使用命名空間 – Nkosi

+0

看起來第一部分也沒有,我得到一個ArgumentNullException指向啓動文件中的DefaultConnnection – Hypenate