Asp.NetCore 利用SqlSugar连接数据库

1、安装SqlSugarCore包

Asp.NetCore 利用SqlSugar连接数据库_第1张图片

2、配置appsettings.json连接字符串(.NetCore没有Web.config了)

"ConnectionStrings": {
    //Sqlserver
    "BaseDbSqlServer": "data source=192.168.1.1;Initial Catalog=TestDb;User ID=sa;Password=sa;MultipleActiveResultSets=true",
    //Oracle
    "BaseDbOracle": "data source=192.168.1.1;password=sa;User id=TestDb;Incr Pool Size=5;Decr Pool Size=2;"
    //MySql
   "BaseDbMySql": "data source=192.168.1.;Database=TestDb;User ID=sa;Password=sa;pooling=true;port=3306;sslmode=none;CharSet=utf8;"
  }

3、新建类,读取Json配置文件

public class SqlsugarBase
    {
        /// 
        /// 读取json配置文件
        /// 
        private static IConfigurationRoot Configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .Build();
        /// 
        /// 读取配置文件下的连接字符串
        /// 
        string connectionString = Configuration.GetSection("ConnectionStrings").GetSection("BaseDbSqlServer").Value;
        //string connectionString= Configuration.GetConnectionString("BaseDbSqlServer");

        public SqlSugarClient db => GetInstance();
        SqlSugarClient GetInstance()
        {
            var db = new SqlSugarClient(
                new ConnectionConfig
                {
                    ConnectionString = connectionString,
                    DbType = DbType.SqlServer,//数据库类型
                    IsShardSameThread = true,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                }
            );
            return db;
        }
    }

4、继承SqlsugarBase类

public class TestService: SqlsugarBase
    {
        public List GetUserList()
        {
            List list = new List();
            list = db.Queryable().Where("SysUserId='1'").ToList();
            return list;
        }
    }

你可能感兴趣的:(SqlSugar,数据库,数据库,asp.net)