(转自:https://blog.csdn.net/jayshehe/article/details/79796601)
配置读取
.net core下读取配置还是有点麻烦的,本身没有System.Configuration.dll,所以在进行配置前需要自行引用Microsoft.Extensions.Configuration,截图如下:
这样的话我们就可以配置读取的相关编码了,比如我们数据库的链接字符串,在appsettings.json添加对应的数据库配置:
"ConnectionStrings": {"TestDb":"server=localhost;port=3306;database=mytest;user=test;password=123456;charset=utf8;"}
读取配置相关代码如下:
publicclassAppSetting{privatestaticreadonlyobjectobjLock =newobject();privatestaticAppSetting instance =null;privateIConfigurationRoot Config {get; }privateAppSetting() {varbuilder =newConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional:false, reloadOnChange:true); Config = builder.Build(); }publicstaticAppSettingGetInstance() {if(instance ==null) {lock(objLock) {if(instance ==null) { instance =newAppSetting(); } } }returninstance; }publicstaticstringGetConfig(stringname) {returnGetInstance().Config.GetSection(name).Value; }}
这样就可以直接读取对应的配置信息啦:
stringCONNECTION_STRING = AppSetting.GetConfig("ConnectionStrings:TestDb");
1
数据库操作
数据库相关操作还是建议使用Dapper以及Dapper.Contrib,比较轻量,也比较方便。
Dapper相信大家还是比较熟悉的,这里简单说下Dapper.Contrib,基于Dapper的扩展方法,封装了如下方法:
T Get(id);
IEnumerable GetAll();
int Insert(T obj);
int Insert(Enumerable list);
bool Update(T obj);
bool Update(Enumerable list);
bool Delete(T obj);
bool Delete(Enumerable list);
bool DeleteAll();
这样对应你应用的简单的CRUD方法可以很轻松的搞定的。比如下面几个例子:
//根据主键Id查询using(varconn = DatabaseManager.GetConnection(DatabaseManager.DBName)){awaitconn.OpenAsync();returnawaitconn.GetAsync(id);}
新增数据:
//新增using(varconn = DatabaseManager.GetConnection(DatabaseManager.DBName)){awaitconn.OpenAsync();awaitconn.InsertAsync(entity);}
修改数据:
//修改using(varconn = DatabaseManager.GetConnection(DatabaseManager.DBName)){awaitconn.OpenAsync();awaitconn.UpdateAsync(entity);}
需要注意的是,需要给对应的实体加上特性:
[Table("User")]publicclassUserModel{ [Key]publicintId {get;set; }publicstringUserName {get;set; }publicstringRemark {get;set; }}
[Table(“Tablename”)] 标识对应的表名
[Key] 对应的主键
[ExplicitKey] 如果主键不是自增长的,用此标识
[Write(true/false)] 该字段是否可被写入