ParrySMS 2018-03-29
配置读取
.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,比较轻量,也比较方便。
Dapper相信大家还是比较熟悉的,这里简单说下Dapper.Contrib,基于Dapper的扩展方法,封装了如下方法:
这样对应你应用的简单的CRUD方法可以很轻松的搞定的。比如下面几个例子:
//根据主键Id查询 using (var conn = DatabaseManager.GetConnection(DatabaseManager.DBName)) { await conn.OpenAsync(); return await conn.GetAsync<UserModel>(id); }
新增数据:
//新增 using (var conn = DatabaseManager.GetConnection(DatabaseManager.DBName)) { await conn.OpenAsync(); await conn.InsertAsync(entity); }
修改数据:
//修改 using (var conn = DatabaseManager.GetConnection(DatabaseManager.DBName)) { await conn.OpenAsync(); await conn.UpdateAsync(entity); }
需要注意的是,需要给对应的实体加上特性:
[Table("User")] public class UserModel { [Key] public int Id { get; set; } public string UserName { get; set; } public string Remark { get; set; } }