配置读取
.net core下读取配置还是有点麻烦的,本身没有System.Configuration.dll
,所以在进行配置前需要自行引用Microsoft.Extensions.Configuration
,如下:
这样的话我们就可以配置读取的相关编码了,比如我们数据库的链接字符串,在appsettings.json
添加对应的数据库配置:
"ConnectionStrings": { "TestDb": "server=localhost;port=3306;database=mytest;user=test;password=123456;charset=utf8;" }
读取配置相关代码如下:
public class AppSetting { private static readonly object objLock = new object(); private static AppSetting instance = null; private IConfigurationRoot Config { get; } private AppSetting() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); Config = builder.Build(); } public static AppSetting GetInstance() { if (instance == null) { lock (objLock) { if (instance == null) { instance = new AppSetting(); } } } return instance; } public static string GetConfig(string name) { return GetInstance().Config.GetSection(name).Value; } }
这样就可以直接读取对应的配置信息啦:
string CONNECTION_STRING = AppSetting.GetConfig("ConnectionStrings:TestDb");
数据库操作
数据库相关操作还是建议使用Dapper
以及Dapper.Contrib
,比较轻量,也比较方便。
创表
CREATE TABLE friends ( id INT ( 3 ) NOT NULL, NAME VARCHAR ( 8 ) NOT NULL, pass VARCHAR ( 20 ) NOT NULL ); INSERT INTO friends VALUES ( '004', '王六', 'dasd' ); SELECT * FROM friends