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
    }
}
时间: 2024-10-12 04:09:34

ServiceBase 备份的相关文章

WEB页面,WEB环境版本,数据库,整站备份脚本

#!/bin/bash # #WEB页面,WEB环境版本,数据库,整站备份脚本 #当发生某个原因导致整个服务器无法恢复时,利用上面备份的相关数据即可重做一台一样的服务器 date_a=`date +%Y%m%d-%H%M%S` mkdir -p /web_bak/${date_a}/conf &> /dev/null mkdir -p /web_bak/${date_a}/web &> /dev/null mkdir -p /web_bak/${date_a}/mysql &a

web网站升级备份脚本

#!/bin/bash # 一般web页面升级都是直接替换根目录下的对应文件,因此升级前备份对应的目录或者文件即可 web=/var/www/html #web根目录 dd="/data /admin /ps /css /bbs*" #web根目录下要备份的目录与文件,把要备份的目录或者文件,写入这个变量,可以使用*通配符. mkdir -p /web_bak &> /dev/null #创建备份所在的目录 for dd in $dd;do #列表循环 date_bak=

C# 备份、还原、拷贝远程文件夹

最近一直都很忙,非常抱歉好久没有写过博客了.最近遇到拷贝远程文件的一些工作,比如我们发布的web站点的时候,开发提供一个zip压缩包,我们需要上传到远程的服务器A,然后在部署(文件拷贝)到远程环境B和C,ABC都在一个局域网里面. 首先我们需要一个工具类来转换文件路径,本地地址与远程地址的转换 比如192.168.0.1上的D:\test 转换 为\\192.168.0.1\D$\test,文件路径的拼接, public class PathUtil { public static string

SqlServer定时备份数据库和定时杀死数据库死锁解决

PS:Sqlserver 2008 R2,windows 8 64位 1.备份数据库 因为要备份,我们就要用到Sqlserver的代理,默认数据库的代理是不开启的.需要我们手动开启的. 执行备份数据库脚本,现在将脚本公布,其实将这一段代码中需要保存的文件路径和数据库名称替换一下就可以实现备份了.但是还没有达到定时备份的目的 ? 1 2 3 4 5 6 7 8 9 10 11 --自动备份并保存最近5天的SQL数据库作业脚本 宋彪 20130310 DECLARE @filename VARCHA

mysql5.7 innodb数据库备份工具Xtrabackup的安装

mysql5.7 innodb数据库备份工具Xtrabackup的安装     wget mhttps://www.percona.com/downloads/XtraBackup/Percona-XtraBackup-2.4.7/binary/redhat/6/x86_64/percona-xtrabackup-24-2.4.7-1.el6.x86_64.rpm Mysql5.7需要安装XtraBackup 2.4.1以上版本 官网地址 https://www.percona.com/down

bzoj1150 [CTSC2007]数据备份

Description 你在一家 IT 公司为大型写字楼或办公楼(offices)的计算机数据做备份.然而数据备份的工作是枯燥乏味的,因此你想设计一个系统让不同的办公楼彼此之间互相备份,而你则坐在家中尽享计算机游戏的乐趣.已知办公楼都位于同一条街上.你决定给这些办公楼配对(两个一组).每一对办公楼可以通过在这两个建筑物之间铺设网络电缆使得它们可以互相备份.然而,网络电缆的费用很高.当地电信公司仅能为你提供 K 条网络电缆,这意味着你仅能为 K 对办公楼(或总计2K个办公楼)安排备份.任一个办公楼

mysql备份还原

先记录一下mysql的备份和还原指令: 备份使用mysqldump mysqldump test>e:\testback.sql test为所有备份的数据库 还原使用mysql指令 mysql> use test; Database changed 先切换到要还原的数据库下 mysql> source e:\testback.sql 还原数据库

rsync存储服务器-全网备份

一.rsync功能介绍: 复制 (同步)的工具 全量及增量 本地和远程 Rsync英文全称为Remotesynchronization 本地复制cp(全量备份),rsunc也有此功能(增量) 远程复制scp(全量备份),rsync也有此功能(增量) 删除工具rm,rsync也有此功能 二. Rsync的特性 支持拷贝特殊文件如链接文件,设备等 可以有排除指定文件或目录同步的功能,相当于打包命令tar的排除功能 可以做到保持原文件或目录的权限.时间.软硬链接.属主.组等所有属性均不改变  - p

【铜】第131篇 融合一对一canvas视频录制到备份上(二)简版做成及追加图片过程周四

关键词:一对一canvas视频录制, 简版做成,追加图片过程 一.一对一视频录制 1.1 往备份上布录制-----------------bug处理 现在不知道,网页录制都依赖哪些文件,现在需要一个一个的去除.现在去除差不多了,如下: 经过整理发现,仅仅需要两个文件,就能实现录制.如下: 简版访问地址如下: http://localhost:9001/record-canvas-drawings.html#no-back-button 二.追加图片过程 2.1 学生端追加拍照 <li><