ServiceBase 备份
using CanDoo.Contracts;
using CanDoo.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanDoo.Data;
using System.Linq.Expressions;
using CanDoo.Extensions;
using CanDoo.Core.Caching;
using Mehdime.Entity;
using System.Data.Entity;
using System.Linq.Dynamic;
using CanDoo.Core.Data.Extensions;
using CanDoo.Filter;
using CanDoo.Exceptions;
using System.Diagnostics.Contracts; namespace CanDoo.Data.Entity.Services
{
public abstract class ServiceBase<TEntity> : ServiceBase<TEntity, Guid>
where TEntity : class, IEntity<Guid>,IEntity, new()
{
}
public abstract class ServiceBase<TEntity, TKey> : IServiceBase<TEntity, TKey>
where TEntity : class, IEntity<TKey>, new()
{
#region 属性
public virtual IQueryable<TEntity> Entities
{
get
{
return Repository.Entities;
}
} public IRepository<TEntity, TKey> Repository { get; set; } /// <summary>
/// 很快要删除此属性
/// </summary>
private IUnitOfWork UnitOfWork
{
get
{
return Repository.UnitOfWork;
}
}
#endregion public IDbContextScopeFactory DbScopeFactory { get; set; } public ServiceBase()
{
OnDeleting += BeforeDelete;
OnDeleted += AfterDelete;
OnUpdating += BeforeUpdate;
OnUpdated += AfterUpdate;
OnAdding += BeforeAdd;
OnAdded += AfterAdd;
OnQuerying += AfterBeforeQuery;
OnQueried += AfterQuery;
} /// <summary>
/// 这个改成内部方法,,读出来总要在操作单元(事务中使用,不然读出来也无法惰性加载
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public TEntity GetById(TKey Id)
{
return Repository.GetByKey(Id);
} /// <summary>
/// 根据id读出只读实体,在action内,实体可以惰性加载
/// </summary>
/// <param name="Id"></param>
/// <param name="readOnlyAcion"></param>
public void GetById(TKey Id, Action<TEntity> readOnlyAcion)
{
using (var scope = DbScopeFactory.CreateReadOnly())
{
TEntity entity = GetById(Id);
readOnlyAcion(entity);
}
} /// <summary>
/// 根据id读出实体,在action内,实体可以惰性加载,如果查不数据,new一个对象出来
/// </summary>
/// <param name="Id"></param>
/// <param name="readOnlyLoadAction"></param>
public void LoadById(TKey Id, Action<TEntity> readOnlyLoadAction)
{
using (var scope = DbScopeFactory.CreateReadOnly())
{
TEntity entity = GetById(Id);
if (entity == null)
{
entity = new TEntity();
entity.Id = Id;
}
readOnlyLoadAction(entity);
}
}
#region GetPaged
public PageResult<TResult> GetPaged<TResult>(Expression<Func<TEntity, TResult>> selector, System.Linq.Expressions.Expression<Func<TEntity, bool>> filter = null,
string sortExpression = "", int pagesize = 10, int pageindex = 0, string includeProperties = "")
{
using (var dbContextScope = DbScopeFactory.CreateReadOnly())
{
var query = Entities; if (filter != null)
{
query = query.Where(filter);
}
if (!string.IsNullOrEmpty(includeProperties))
{
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
if (!string.IsNullOrEmpty(sortExpression))
{
query = query.SortBy(sortExpression);
}
else
{
query = query.SortBy("Id desc");
}
var selectedQuery = query.Select(selector); selectedQuery = selectedQuery.Skip(pagesize * pageindex).Take(pagesize); var data = selectedQuery.ToArray();
//Entities.Where(filter).OrderBy(p => p.Id).Skip(pagesize * pageindex).Take(pagesize).ToArray(); return new PageResult<TResult> { Data = data, Total = this.Repository.Count(filter) };
}
} public PageResult<TResult> GetPaged<TResult>(System.Linq.Expressions.Expression<Func<TEntity, bool>> filter = null, Expression<Func<TEntity, TResult>> selector = null,
Func<IQueryable<TResult>, IOrderedQueryable<TResult>> orderBy = null, int pagesize = 10, int pageindex = 0, string includeProperties = "")
{
//using (var dbContextScope = _dbContextScopeFactory.Create())
{
IQueryable<TEntity> query = this.Entities; if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
} IQueryable<TResult> qResult = query.Select(selector); IOrderedQueryable<TResult> qSort;
if (orderBy != null)
{
qSort = orderBy(qResult);
qResult = qSort.Skip(pagesize * pageindex).Take(pagesize);
}
else
{
qResult = qResult.Skip(pagesize * pageindex).Take(pagesize);
}
return new PageResult<TResult> { Data = qResult.ToArray(), Total = query.Count() };
}
} public IQueryable<TEntity> Get(System.Linq.Expressions.Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "")
{ //q.Skip(GridList.PageIndex * GridList.PageSize).Take(GridList.PageSize).ToList() IQueryable<TEntity> query = this.Entities;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query);
}
else
{
return query;
}
} #endregion #region 增删改查
#region Add public OperationResult AddEntity(TEntity Entity)
{
Entity.CheckNotNull("Entity"); using (var dbContextScope = DbScopeFactory.Create())
{
var result = OperationResult.NoChanged;
if (OnAdding != null)
{
result = BeforeAdd(new[] { Entity.Id }, new[] { Entity });
if (result.ResultType != OperationResultType.NoChanged && result.ResultType != OperationResultType.Success)
return result;
}
Repository.Insert(Entity);//
try
{
result = dbContextScope.SaveChanges() > 0 ? OperationResult.Success : OperationResult.NoChanged;
}
catch (Exception ex)
{
result = new OperationResult(OperationResultType.Error, ex.Message);
} //只有操作成功才执行AfterAdd事件
if (result.ResultType == OperationResultType.Success && OnAdded != null)
{
AfterAdd(new[] { Entity.Id }, new[] { Entity });
} return result;
}
} public OperationResult AddEntity(IEnumerable<TEntity> entities)
{
entities.CheckNotNull("entities");
using (var dbContextScope = DbScopeFactory.Create())
{
Repository.Insert(entities);
return dbContextScope.SaveChanges() > 0 ? new OperationResult(OperationResultType.Success, "数据添加成功!") : new OperationResult(OperationResultType.NoChanged);
}
}
public OperationResult AddEntity(TKey id, Func<TEntity, OperationResult> addFunc)
{
using (var scope = DbScopeFactory.Create())
{
var result = OperationResult.NoChanged;
try
{
TEntity entity = new TEntity();
entity.Id = id;
result = addFunc(entity); if (result.ResultType == OperationResultType.Success)
{
//执行添加事件
result = BeforeAdd?.Invoke(new[] { id }, new[] { entity }) ?? OperationResult.Success;
if (result == null || result.ResultType == OperationResultType.Success)
{
Repository.Insert(entity);
result = scope.SaveChanges() > 0 ? OperationResult.Success : OperationResult.NoChanged;
}
} if (result.ResultType == OperationResultType.Success)
{
AfterAdd?.Invoke(new[] { id }, new[] { entity });
}
}
catch (Exception ex)
{
result = new OperationResult(OperationResultType.Error, ex.Message, ex);
}
return result;
}
}
#endregion
#region Delete
public OperationResult DeleteEntity(TEntity Entity)
{
Entity.CheckNotNull("Entity");
return Repository.Delete(Entity) > 0
? new OperationResult(OperationResultType.Success, "数据删除成功!")
: new OperationResult(OperationResultType.NoChanged);
}
public OperationResult DeleteEntity(TKey id)
{
using (var dbContextScope = DbScopeFactory.Create())
{
return Repository.Delete(id) > 0
? new OperationResult(OperationResultType.Success, "数据删除成功!")
: new OperationResult(OperationResultType.NoChanged);
}
}
public OperationResult DeleteEntity(IEnumerable<TEntity> Entities)
{
Entities.CheckNotNull("Entities");
using (var dbContextScope = DbScopeFactory.Create())
{
return Repository.Delete(Entities) > 0
? new OperationResult(OperationResultType.Success, "数据删除成功!")
: new OperationResult(OperationResultType.NoChanged);
}
} public OperationResult DeleteEntity(List<TKey> ids)
{
ids.CheckNotNull("ids");
using (var dbContextScope = DbScopeFactory.Create())
{
Repository.Delete(p => ids.Contains(p.Id));
return dbContextScope.SaveChanges() > 0
? new OperationResult(OperationResultType.Success, "数据删除成功!")
: new OperationResult(OperationResultType.NoChanged);
}
} public OperationResult DeleteEntity(Expression<Func<TEntity, bool>> predicate)
{
using (var dbContextScope = DbScopeFactory.Create())
{
return Repository.Delete(predicate) > 0
? new OperationResult(OperationResultType.Success, "数据删除成功!")
: new OperationResult(OperationResultType.NoChanged);
}
}
#endregion
#region Update public OperationResult UpdateEntity(IEnumerable<TEntity> Entities)
{
Entities.CheckNotNull("Entities");
using (var dbContextScope = DbScopeFactory.Create())
{
UnitOfWork.TransactionEnabled = true;
foreach (var item in Entities)
{
Repository.Update(item);
} return UnitOfWork.SaveChanges() > 0
? new OperationResult(OperationResultType.Success, "数据更新成功!")
: new OperationResult(OperationResultType.NoChanged);
}
} public OperationResult UpdateEntity(TEntity Entity)
{
Entity.CheckNotNull("Entity");
using (var dbContextScope = DbScopeFactory.Create())
{
return Repository.Update(Entity) > 0
? new OperationResult(OperationResultType.Success, "数据更新成功!")
: new OperationResult(OperationResultType.NoChanged);
}
}
public OperationResult UpdateEntity(TKey id, Func<TEntity, OperationResult> updateFunc)
{
using (var scope = DbScopeFactory.Create())
{
var result = OperationResult.NoChanged;
try
{
TEntity entity = GetById(id);
if (entity == null)
{
return new OperationResult(OperationResultType.QueryNull, "你要更新的数据找不到,可能已经被删除。");
} result = updateFunc(entity); if (result.ResultType == OperationResultType.Success)
{
//执行更新前事件
result = BeforeUpdate?.Invoke(new[] { id }, new[] { entity }) ?? OperationResult.Success; ;
if (result.ResultType == OperationResultType.Success)
//Repository.Update(entity); 这个不需要了,对象已经在被跟踪状态
result = scope.SaveChanges() > 0 ? OperationResult.Success : OperationResult.NoChanged;
} if (result.ResultType == OperationResultType.Success)
{
AfterUpdate?.Invoke(new[] { id }, new[] { entity });
} }
catch (Exception ex)
{
result = new OperationResult(OperationResultType.Error,ex.Message,ex);
}
return result;
}
}
#endregion #endregion #region AttachEntity public TEntity AttachEntity(TEntity entity)
{
return this.Repository.AttachEntity(entity);
} public void AttachEntity(ICollection<TEntity> existItems, TKey[] newItemIDs)
{
throw new NotImplementedException();
} public TEntity AttachEntityByKey(TKey keyID)
{
TEntity entity = new TEntity();
entity.Id = keyID;
return AttachEntity(entity);
}
/// <summary>
/// 更新原集合中的元素
/// </summary>
/// <typeparam name="TData"></typeparam>
/// <typeparam name="TDataKey"></typeparam>
/// <param name="orignEntities"></param>
/// <param name="newEntities"></param>
protected void ReplaceEntity<TData>(ICollection<TData> orignEntities, ICollection<TData> newEntities)
{
//删除旧的 orignEntities.Where(p => newEntities.Contains(p) == false).ToList().ForEach(deleted => orignEntities.Remove(deleted));
//添加新的
newEntities.Where(p => orignEntities.Contains(p) == false).ToList().ForEach(added => orignEntities.Add(added));
} #endregion #region Event
public event Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> OnAdded; public event Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> OnAdding; public event Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> OnDeleted; public event Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> OnDeleting;
public event Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> OnQueried; public event Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> OnQuerying; public event Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> OnUpdated; public event Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> OnUpdating;
#endregion #region Event Handler 事件处理器
public Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> AfterAdd;
public Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> AfterBeforeQuery;
public Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> AfterDelete;
public Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> AfterQuery;
public Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> AfterUpdate;
public Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> BeforeAdd;
public Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> BeforeDelete;
public Func<IEnumerable<TKey>, IEnumerable<TEntity>, OperationResult> BeforeUpdate;
#endregion #region 事务操作 public void KeepReading(Action readFromeDbOnlyAction)
{
using (var dbContextScope = DbScopeFactory.CreateReadOnly())
{
readFromeDbOnlyAction();
}
}
public OperationResult Save(Func<OperationResult> saveAction)
{
using (var dbContextScope = DbScopeFactory.Create())
{
OperationResult or = OperationResult.NoChanged; #region 执行保存过程
or = saveAction?.Invoke();
if (or.ResultType != OperationResultType.Success && or.ResultType != OperationResultType.NoChanged)
{
return or;
}
#endregion
try
{
or = dbContextScope.SaveChanges() > 0 ? OperationResult.Success : OperationResult.NoChanged;
}
catch (CanDooException ex)
{
or = new OperationResult(OperationResultType.Error, ex.Message);
} return or;
}
} #endregion
}
}
ServiceBase 备份的更多相关文章
- windows服务自动备份数据库
最近写了几个windows服务用于自动备份与删除数据: services代码如下: public partial class Service1 : ServiceBase { public Servi ...
- SQL Server 大数据搬迁之文件组备份还原实战
一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 解决方案(Solution) 搬迁步骤(Procedure) 搬迁脚本(SQL Codes) ...
- MySQL 系列(四)主从复制、备份恢复方案生产环境实战
第一篇:MySQL 系列(一) 生产标准线上环境安装配置案例及棘手问题解决 第二篇:MySQL 系列(二) 你不知道的数据库操作 第三篇:MySQL 系列(三)你不知道的 视图.触发器.存储过程.函数 ...
- MongoDB备份(mongodump)和恢复(mongorestore)
MongoDB提供了备份和恢复的功能,分别是MongoDB下载目录下的mongodump.exe和mongorestore.exe文件 1.备份数据使用下面的命令: >mongodump -h ...
- 分享一个MySQL分库分表备份脚本(原)
分享一个MySQL分库备份脚本(原) 开发思路: 1.路径:规定备份到什么位置,把路径(先判断是否存在,不存在创建一个目录)先定义好,我的路径:/mysql/backup,每个备份用压缩提升效率,带上 ...
- 数据库备份并分离日志表(按月)sh 脚本
#!/bin/sh year=`date +%Y` month=`date +%m` day=`date +%d` hour=`date +%H` dir="/data/dbbackup/f ...
- 我的MYSQL学习心得(十四) 备份和恢复
我的MYSQL学习心得(十四) 备份和恢复 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) ...
- Linux 中我该如何备份系统
系统备份概述 在前面的一些文章中,我反复提到经常会把系统搞崩溃,所以备份系统就是一件不容忽视的事情.由于 Linux 系统本身的优越性,系统的备份和还原还是比较容易的.主要表现在以下方面: Linux ...
- Atitit.每月数据采集与备份 v4
Atitit.每月数据采集与备份 v4 备份检查表 r12 00cate 00item im Inputmethod ok ok Log Log ok cyar Cyar log ... ok c ...
随机推荐
- 【BZOJ 3048】【USACO2013 Jan】Cow Lineup 滑块思想
昨天下午想了好久没想出来,果然是很弱,思考能力低下. 用的类似单调队列的思想,维护一个长度为$k+1$的滑块,每次统计下$ans$就可以了 #include<cstdio> #includ ...
- <UL>中<li>标签前编号图片的简单调用
<style type="text/css"> ul li{ list-style-type:none} .men ul{ background:url(http:// ...
- Android Studio插件安装及使用Genymotion模拟器
Android Studio自带的模拟器速度已经比Eclipse插件的快一点了,但是还不够暴力,不够爽.现在来说说最暴力的Genymotion模拟器如何结合AS 使用.首先上Genymotion官网下 ...
- js 时间与时间戳的转换
一:时间转时间戳:javascript获得时间戳的方法有四种,都是通过实例化时间对象 new Date() 来进一步获取当前的时间戳 1.var timestamp1 = Date.parse(n ...
- 【codevs1012】最大公约数和最小公倍数
题目描述 Description 输入二个正整数x0,y0(2<=x0<100000,2<=y0<=1000000),求出满足下列条件的P,Q的个数 条件: 1.P,Q是正整 ...
- 实现socket非阻塞设置
刚开始学习,难免有些疏漏之处,请各位多多指教. 程序亲测可以使用.废话不多说. 网络IO模型分为阻塞IO.非阻塞IO.异步IO.IO复用.信号驱动IO. 阻塞IO: 有数据时,直接读:没有数据时,等待 ...
- Leetcode 270. Closest Binary Search Tree Value
Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...
- SQL Server附加数据库时失败,提示:“未重新生成日志,因为有不止一个日志文件”
这个只能是试一下的方法,但不一定能成功,可以尝试如下几个方法: 1.登录远程桌面,然后以.登录SQL Server,并以Windows身份登录,然后再附加数据库时把日志文件删除. 2.试下这个脚本: ...
- [JavaWeb 用MyEclipse分别创建最简单的JSP程序和Servlet程序]
最近看了子柳的<淘宝技术这十年>,其中讲到因为负载和连接池问题,淘宝当年迫不得已从SUN请来一对工程师从LAMP架构转到Java+Oracle.作为一个PHP为“母语”的程序仔,真是感到压 ...
- BZOJ3813: 奇数国
传送门 欧拉函数+线段树 因为只有60个素数,所以把状态压成long long的形式.用线段树维护区间和和区间和中有多少个质数.然后xjb搞搞就行了,具体参见代码. //BZOJ 3813 //by ...