using Furion; using Furion.DependencyInjection; using Microsoft.Extensions.Caching.Memory; using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoadFlow.Data { public class RoadFlowRepository : IRoadFlowRepository, ITransient where T:RoadFlow.Model.BaseEntity,new() { protected readonly IMemoryCache _memoryCache; protected readonly ISqlSugarRepository repository; protected readonly SqlSugarClient db; protected readonly string CACHEKEY = "roadflow_cache_" + typeof(T).FullName; public RoadFlowRepository() { _memoryCache = App.GetService< IMemoryCache > (); repository = App.GetService(); db = repository.Context; //db选择 db.ChangeDatabase("118_3310_ewide"); } /// /// 获取所有的数据对象并缓存 /// /// public virtual List GetAll() { return _memoryCache.GetOrCreate(CACHEKEY, v => { return db.Queryable().ToList(); }); } /// /// 按Id获取一个对象 /// /// /// public virtual T GetOneById(string id) { List list = GetAll(); return list.Find(p => p.Id == id); } /// /// 按条件获取一个对象 /// /// /// public virtual T GetOneBy(Predicate predicate) { return GetAll().Find(predicate); } /// /// 按条件获取列表 /// /// /// public virtual List GetListBy(Predicate predicate) { return GetAll().FindAll(predicate); } /// /// 增加对象 /// /// /// public virtual int Add(T t) { int rtn =db.Insertable(t).ExecuteCommand(); ClearCache(); return rtn; } /// /// 增加多个对象 /// /// /// public virtual int AddRangeList(List ts) { int rtn =db.Insertable(ts).ExecuteCommand(); ClearCache(); return rtn; } /// /// 更新对象 /// /// /// public virtual int Update(T t,bool clearCache=true) { int rtn =db.Updateable(t).ExecuteCommand(); if(clearCache) ClearCache(); return rtn; } /// /// 更新多个对象 /// /// /// public virtual int Update(List ts,bool trans=true) { int rslt = 0; try { if(trans) db.BeginTran(); foreach (var t in ts) { rslt += this.Update(t,false); } if(trans) db.CommitTran(); ClearCache(); } catch { db.RollbackTran(); } return rslt; } /// /// 删除对象(物理) /// /// /// public virtual int Delete(T t) { int rtn =db.Deleteable(t).ExecuteCommand(); ClearCache(); return rtn; } /// /// 删除一批对象(物理) /// /// /// public virtual int Delete(List ts) { int rtn = db.Deleteable(ts).ExecuteCommand(); ClearCache(); return rtn; } /// /// 按条件删除对象 /// /// /// public virtual int DeleteBy(System.Linq.Expressions.Expression> expression) { int rtn =db.Deleteable(expression).ExecuteCommand(); ClearCache(); return rtn; } /// /// 清空缓存 /// public virtual void ClearCache() { _memoryCache.Remove(CACHEKEY); } /// /// 清空缓存 /// public virtual void ClearCache(string id) { _memoryCache.Remove(CACHEKEY + id); } public virtual SqlSugarClient getClient() { // string str =this.db.Ado.Connection.ConnectionString; return this.db; } public virtual void BeginTrans() { this.db.Ado.BeginTran(); } public virtual void CommitTran() { this.db.Ado.CommitTran(); } public virtual void RollbackTran() { this.db.Ado.RollbackTran(); } public virtual string getCacheKey() { return this.CACHEKEY; } } }