博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

net core依赖注入设置数据库连接

Posted on 2023-04-26 15:00  火冰·瓶  阅读(82)  评论(0)    收藏  举报

一、在appsetting.json中设置数据库连接字符串 

{
"ConnectionStrings": {
    "DianXinMySql": "server=localhost;port=3306;user=root;password=password;database=db_name"
},
"Logging": {
    "LogLevel": {
    "Default": "Information",
    "Microsoft.AspNetCore": "Warning"
    }
},
"AllowedHosts": "*"
}

   

二、在Program.cs中添加如下代码

builder.Services.AddDbContext<TelecomDbContext>(options =>
    options.UseMySQL(builder.Configuration.GetConnectionString("DianXinMySql")));


其他写法:
IConfiguration configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", true, true)
    .Build();

//IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).AddJsonFile("appsettings.json").Build();  

builder.Services.AddDbContext<TelecomDbContext>(options =>
{
    options.UseMySQL(configuration.GetConnectionString("DianXinMySql"));
});

 

三、在Controller依赖注入后调用

    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly TelecomDbContext _bd;

        public HomeController(ILogger<HomeController> logger, TelecomDbContext bd)
        {
            _logger = logger;
            _bd = bd;
        }

        public IActionResult Index()
        {   
            var list = _bd.CommonDistributionPtCities.ToList();
            return View();
        }
    }