![](/img/trans.png)
[英].NET Framework and Entity Framework Core: How can I get hold of the connection string
[英]How should I store the entity framework 6 connection string when using .net core
我有一個.net核心REST api項目,它調用一個使用實體框架的.net 4.6程序集。 我還有一個調用該程序集的測試項目。 給出連接字符串的舊方法是在App或web.Config中使用連接字符串
<connectionStrings>
<add name="MyDbContext" connectionString="data source=(LocalDB)\MSSQLLocalDB;AttachDBFilename=|DataDirectory|\TestDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
你的dbContext做了
public MyDbContext(): base("name=MyDbContext")
我假設我必須將信息放在我的appsettings.Json中
"ConnectionStrings": {
"MyDatabase": "Server=(localdb)\\mssqllocaldb;Database=TestDB;Trusted_Connection=True;"
},
但后來我需要改變我的DbContext怎么樣? 以及我的測試項目如何設置連接字符串?
這應該是很多人以前做過的一個簡單的,但我在谷歌搜索中找不到任何例子。 謝謝。
好吧,沒有太多的興趣。 我有一個有效的解決方案,但我不相信我已經做對了,有人有更好的東西嗎?
我創建了一個新的Settings類來保存設置,目前只是DbConnection
public class Settings
{
public string DBConnection { get; set; }
}
然后我將設置放在appsettings.json中
"Settings": {
"DBConnection": "Server=(localdb)\\mssqllocaldb;Database=TestDB;Trusted_Connection=True;"
}
並將此配置綁定到“啟動”中的“設置”對象
private void AddConfigurationSettingsSingleton(IServiceCollection services)
{
var config = new Settings();
Configuration.GetSection("Settings").Bind(config);
services.AddSingleton(config);
}
然后DI將它粘在任何需要的地方。
public class Repository
{
private readonly SkinDbContext dbContext;
public Repository(Settings settings)
{
dbContext = new MyDbContext(settings.DBConnection);
}
任何我的DBContext都接受連接字符串
public class MyDbContext: DbContext
{
public MyDbContext(string connectionString): base(connectionString)
{
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.