这里的默认配置文件指的是项目中的appsettings.json文件,我们可以把一些配置信息保存在里面,比如数据库连接信息。
来吧,看例子:
1、先在appsettings.json文件中写入数据库的连接信息:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"DataBase": { //添加的数据库连接
"Server": "m.xmbygy.com",
"Name": "fdsafdsa",
"UID": "321dwwq",
"PassWord": "sdfewwssva"
}
}
2、在Startup.cs的ConfigureServices中注入上下文类
services.AddTransient();
3、在上下文类EFCoreContext.cs中读取配置信息
public class EFCoreContext : DbContext
{
private IConfiguration Configuration;
//通过构造函数注入Configuration对象
public EFCoreContext(IConfiguration configuration)
{
Configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string server = Configuration["DataBase:Server"];
string name = Configuration["DataBase:Name"];
string uID = Configuration["DataBase:UID"];
string passWord = Configuration["DataBase:PassWord"];
string strConn = $"server = {server}; user id = {uID}; password ={passWord}; database = {name}";
optionsBuilder.UseSqlServer(strConn);//数据库连接
}
}
4、获取成功,如下图:
这就是最简单的一种方法,也是最实用的。