Asp.Net Core 开发之旅之.net core 连接数据库

数据库连接字符串放入配置文件中

打开appsettings.json

添加ConnectionStrings

例子如下:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "BaseDb": "Server=********;Initial Catalog=******;User ID=**;Password=*********;MultipleActiveResultSets=true"
  }
}

 

配置上下文

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Dw.Models.FindLove;
using Dw.Util;

namespace Dw.Models
{
    /// <summary>
    /// 数据访问(SqlServer) 上下文
    /// </summary>
    public class MsSqlDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(Config.GetValue("ConnectionStrings:BaseDb"));
            base.OnConfiguring(optionsBuilder);
        }

        public DbSet<FL_User> FL_User { get; set; }
    }
}

 注意引用安装包:

Microsoft.EntityFrameworkCore 和 Microsoft.EntityFrameworkCore.SqlServer

读取json配置文件辅助类Config

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Extensions.Configuration;

namespace Dw.Util
{
    /// <summary>
    /// 配置文件
    /// </summary>
    public class Config
    {
        #region 根据Key取Value值
        /// <summary>
        /// 根据Key取Value值
        /// </summary>
        /// <param name="key"></param>
        public static string GetValue(string key)
        {
            var configJson = GetJsonConfig();
            return configJson[key];
        }
        #endregion

        #region json配置文件读取
        /// <summary>
        /// json配置文件读取
        /// </summary>
        /// <param name="configFileName"></param>
        /// <param name="basePath"></param>
        /// <returns></returns>
        public static IConfigurationRoot GetJsonConfig(string configFileName = "appsettings.json", string basePath = "")
        {
            basePath = string.IsNullOrWhiteSpace(basePath) ? Directory.GetCurrentDirectory() : basePath;
            var builder = new ConfigurationBuilder().SetBasePath(basePath).AddJsonFile(configFileName);
            return builder.Build();
        }
        #endregion
    }
}

 

posted @ 2019-10-29 14:27  代码沉思者  阅读(7092)  评论(0编辑  收藏  举报