简易项目搭建 Models 层封装
发布于: 2021 年 03 月 06 日
接着上文章的内容,在日志和 json 都简单封装的情况下
我们开始对 Models 层进行封装
Models 主要存放数据库的上下文 Orm 和不同的实体类(PocoModel,ExtendModel)
#Models 层
上下文的操作,因为小型控制台项目,不会涉及大的业务分层,所以选取 SqlSugar 做为 Orm 首选,它具有小巧,轻便,可以使用 Lambda 表达式进行 CURD 操作,和 EntityFramework 有异曲同工之妙,以前项目大多用 EF 来做,后来接触 SqlSugar 之后 ,感受到了它的方便,大多都转了过来
接下来开始使用 SqlSugar,使用其实是一件特点简单的事情 ,大家可以简单看一个官网的使用文档 1,2,3。10 分钟看完,然后就可以开始做项目了
基于自己的使用习惯,我喜欢将与数据库相当的核心内容放在一起,基本的类如下
>
config.cs 数据库参数配置
DbFactory.cs 数据库实例化工厂
HttpRuntimeCache.cs 为 Sqlsugarclient 提供缓存的接口实现
config.cs
public class Config
{
/// <summary>
/// 数据库连接字符串(私有字段)
/// </summary>
private static readonly string _connectionString = ConfigurationManager.ConnectionStrings["SQLDbCon"].ConnectionString;
/// <summary>
/// 数据库连接字符串(公有属性)
/// </summary>
public static string ConnectionString
{
get { return _connectionString; }
}
}
复制代码
DbFactory.cs
public class DbFactory
{
/// <summary>
/// SqlSugarClient属性
/// </summary>
/// <returns></returns>
public static SqlSugarClient GetSqlSugarClient()
{
var db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
ConfigureExternalServices = new ConfigureExternalServices()
{
DataInfoCacheService = new HttpRuntimeCache()
},
IsShardSameThread = true
});
return db;
}
}
复制代码
HttpRuntimeCache.cs
public class HttpRuntimeCache : ICacheService
{
public void Add<V>(string key, V value)
{
HttpRuntimeCacheHelper<V>.GetInstance().Add(key, value);
}
public void Add<V>(string key, V value, int cacheDurationInSeconds)
{
HttpRuntimeCacheHelper<V>.GetInstance().Add(key, value, cacheDurationInSeconds);
}
public bool ContainsKey<V>(string key)
{
return HttpRuntimeCacheHelper<V>.GetInstance().ContainsKey(key);
}
public V Get<V>(string key)
{
return HttpRuntimeCacheHelper<V>.GetInstance().Get(key);
}
public IEnumerable<string> GetAllKey<V>()
{
return HttpRuntimeCacheHelper<V>.GetInstance().GetAllKey();
}
public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
{
var cacheManager = HttpRuntimeCacheHelper<V>.GetInstance();
if (cacheManager.ContainsKey(cacheKey))
{
return cacheManager[cacheKey];
}
else
{
var result = create();
cacheManager.Add(cacheKey, result, cacheDurationInSeconds);
return result;
}
}
public void Remove<V>(string key)
{
HttpRuntimeCacheHelper<V>.GetInstance().Remove(key);
}
}
internal class HttpRuntimeCacheHelper<V>
{
#region 全局变量
private static HttpRuntimeCacheHelper<V> _instance = null;
private static readonly object _instanceLock = new object();
#endregion
#region 构造函数
private HttpRuntimeCacheHelper() { }
#endregion
#region 属性
/// <summary>
///根据key获取value
/// </summary>
/// <value></value>
public V this[string key]
{
get { return (V)HttpRuntime.Cache[CreateKey(key)]; }
}
#endregion
#region 公共函数
/// <summary>
/// key是否存在
/// </summary>
/// <param name="key">key</param>
/// <returns> /// 存在<c>true</c> 不存在<c>false</c>. /// /// </returns>
public bool ContainsKey(string key)
{
return HttpRuntime.Cache[CreateKey(key)] != null;
}
/// <summary>
/// 获取缓存值
/// </summary>
/// <param name="key">key</param>
/// <returns></returns>
public V Get(string key)
{
return (V)HttpRuntime.Cache.Get(CreateKey(key));
}
/// <summary>
/// 获取实例 (单例模式)
/// </summary>
/// <returns></returns>
public static HttpRuntimeCacheHelper<V> GetInstance()
{
if (_instance == null)
lock (_instanceLock)
if (_instance == null)
_instance = new HttpRuntimeCacheHelper<V>();
return _instance;
}
/// <summary>
/// 插入缓存(默认20分钟)
/// </summary>
/// <param name="key"> key</param>
/// <param name="value">value</param>
public void Add(string key, V value)
{
Add(key, value, 60 * 20);
}
/// <summary>
/// 插入缓存
/// </summary>
/// <param name="key"> key</param>
/// <param name="value">value</param>
/// <param name="cacheDurationInSeconds">过期时间单位秒</param>
public void Add(string key, V value, int cacheDurationInSeconds)
{
Add(key, value, cacheDurationInSeconds, CacheItemPriority.Default);
}
/// <summary>
/// 插入缓存.
/// </summary>
/// <param name="key">key</param>
/// <param name="value">value</param>
/// <param name="cacheDurationInSeconds">过期时间单位秒</param>
/// <param name="priority">缓存项属性</param>
public void Add(string key, V value, int cacheDurationInSeconds, CacheItemPriority priority)
{
string keyString = CreateKey(key);
HttpRuntime.Cache.Insert(keyString, value, null,
DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null);
}
/// <summary>
/// 插入缓存.
/// </summary>
/// <param name="key">key</param>
/// <param name="value">value</param>
/// <param name="cacheDurationInSeconds">过期时间单位秒</param>
/// <param name="priority">缓存项属性</param>
public void Add(string key, V value, int
cacheDurationInSeconds, CacheDependency dependency, CacheItemPriority priority)
{
string keyString = CreateKey(key);
HttpRuntime.Cache.Insert(keyString, value,
dependency, DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null);
}
/// <summary>
/// 删除缓存
/// </summary>
/// <param name="key">key</param>
public void Remove(string key)
{
HttpRuntime.Cache.Remove(CreateKey(key));
}
/// <summary>
/// 清除所有缓存
/// </summary>
public void RemoveAll()
{
System.Web.Caching.Cache cache = HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = cache.GetEnumerator();
ArrayList al = new ArrayList();
while (CacheEnum.MoveNext())
{
al.Add(CacheEnum.Key);
}
foreach (string key in al)
{
cache.Remove(key);
}
}
/// <summary>
/// 清除所有包含关键字的缓存
/// </summary>
/// <param name="removeKey">关键字</param>
public void RemoveAll(Func<string, bool> removeExpression)
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
var allKeyList = GetAllKey();
var delKeyList = allKeyList.Where(removeExpression).ToList();
foreach (var key in delKeyList)
{
HttpRuntime.Cache.Remove(key); ;
}
}
/// <summary>
/// 获取所有缓存key
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetAllKey()
{
IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
yield return CacheEnum.Key.ToString();
}
}
#endregion
#region 私有函数
/// <summary>
///创建KEY
/// </summary>
/// <param name="key">Key</param>
/// <returns></returns>
private string CreateKey(string key)
{
return key;
}
#endregion
}
复制代码
Models 层完成
划线
评论
复制
发布于: 2021 年 03 月 06 日阅读数: 18
版权声明: 本文为 InfoQ 作者【happlyfox】的原创文章。
原文链接:【http://xie.infoq.cn/article/9d225bb0a0645afb6662fbd3e】。文章转载请联系作者。
happlyfox
关注
公众号 程序员工具集 2021.02.18 加入
博客 [www.zhouhuibo.club] 分享优秀的开源项目、学习资源和常用工具。谈论新闻热点、职场经验、学习感悟。共同进步!
评论