当前位置: 首页 > news >正文

EF 增删改查 泛型方法、类

1.定义泛型类

namespace Crm.Data.Logic.Repository
{
    public abstract class AbstractRepository<TC, T> : IDisposable
        where TC : DbContext, new()
        where T : class
    {
        private TC _entities = new TC();
        private bool _disposed;
        protected TC Context
        {
            get
            {
                return _entities;
            }
            set
            {
                _entities = value;
            }
        }
        public virtual IQueryable<T> All
        {
            get
            {
                return GetAll();
            }
        }
        public virtual IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
        {
            IQueryable<T> queryable = _entities.Set<T>();
            return includeProperties.Aggregate(queryable, (current, expression) => current.Include(expression));
        }
        public virtual IQueryable<T> GetAll()
        {
            return _entities.Set<T>();
        }
        public virtual T Find(params object[] keyValues)
        {
            return _entities.Set<T>().Find(keyValues);
        }
        public virtual IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
        {
            return _entities.Set<T>().Where(predicate);
        }
        public virtual void Add(T entity)
        {
            _entities.Set<T>().Add(entity);
        }

        public virtual void BulkInsert(List<T> list)
        {
            var tblName = typeof(T).Name;
            BulkInsert(_entities.Database.Connection.ConnectionString, tblName, list);
        }

        public static void BulkInsert(string connection, string tableName, IList<T> list)
        {
            using (var bulkCopy = new SqlBulkCopy(connection))
            {
                bulkCopy.BatchSize = list.Count;
                bulkCopy.DestinationTableName = tableName;

                var table = new DataTable();
                var props = TypeDescriptor.GetProperties(typeof(T))
                    //Dirty hack to make sure we only have system data types
                    //i.e. filter out the relationships/collections
                                           .Cast<PropertyDescriptor>()
                                           .Where(propertyInfo => propertyInfo.PropertyType.Namespace != null
                                               && propertyInfo.PropertyType.Namespace.Equals("System"))
                                           .ToArray();

                foreach (var propertyInfo in props)
                {
                    bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
                    table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
                }

                var values = new object[props.Length];
                foreach (var item in list)
                {
                    for (var i = 0; i < values.Length; i++)
                    {
                        values[i] = props[i].GetValue(item);
                    }

                    table.Rows.Add(values);
                }

                bulkCopy.WriteToServer(table);
            }
        }

        public virtual void Delete(T entity)
        {
            _entities.Set<T>().Remove(entity);
        }
        public virtual void Edit(T entity)
        {
            _entities.Entry(entity).State = (EntityState.Modified);
        }
        public virtual void Upsert(T entity, Func<T, bool> insertExpression)
        {
            if (insertExpression(entity))
            {
                Add(entity);
            }
            else
            {
                Edit(entity);
            }
        }
        public virtual void Save()
        {
            _entities.SaveChanges();
        }

        public virtual DataTable PageQuery(int page, int pageSize,
            string sort, string where, out int total)
        {
            var viewName = typeof (T).Name;
            var paras = new List<SqlParameter>
                                {
                                    new SqlParameter("tblName", "dbo."+viewName),
                                    new SqlParameter("fldName", "*"),
                                    new SqlParameter("pageSize", pageSize),
                                    new SqlParameter("page", page),
                                    new SqlParameter("fldSort", sort),
                                    new SqlParameter("strCondition", where),
                                    new SqlParameter("pageCount", SqlDbType.Int){Direction = ParameterDirection.Output},
                                };
            var countParameter = new SqlParameter
            {
                ParameterName = "counts",
                SqlDbType = SqlDbType.Int,
                Direction = ParameterDirection.Output
            };
            var strParameter = new SqlParameter("strSql", SqlDbType.NVarChar, 4000) { Direction = ParameterDirection.Output };

            paras.Add(countParameter);
            paras.Add(strParameter);

            var conn = _entities.Database.Connection.ConnectionString;
            var ds = SqlHelper.ExecuteDataset(conn, CommandType.StoredProcedure,
                                              "dbo.PagedQuery", paras.ToArray());
            total = countParameter.Value == DBNull.Value ? 0 : Convert.ToInt32(countParameter.Value);
            return ds.Tables[0];
        }

        public virtual List<T> PageQueryList(int page, int pageSize,
            string sort, string where, out int total)
        {
            var viewName = typeof(T).Name;
            var paras = new List<SqlParameter>
                                {
                                    new SqlParameter("tblName", "dbo."+viewName),
                                    new SqlParameter("fldName", "*"),
                                    new SqlParameter("pageSize", pageSize),
                                    new SqlParameter("page", page),
                                    new SqlParameter("fldSort", sort),
                                    new SqlParameter("strCondition", where),
                                    new SqlParameter("pageCount", SqlDbType.Int){Direction = ParameterDirection.Output},
                                };
            var countParameter = new SqlParameter
            {
                ParameterName = "counts",
                SqlDbType = SqlDbType.Int,
                Direction = ParameterDirection.Output
            };
            var strParameter = new SqlParameter("strSql", SqlDbType.NVarChar, 4000) { Direction = ParameterDirection.Output };

            paras.Add(countParameter);
            paras.Add(strParameter);

            //var conn = _entities.Database.Connection.ConnectionString;
            //var ds = SqlHelper.ExecuteDataset(conn, CommandType.StoredProcedure,
            //                                  "dbo.PagedQuery", paras.ToArray());
            //total = countParameter.Value == DBNull.Value ? 0 : Convert.ToInt32(countParameter.Value);
            var ret =_entities.Database.SqlQuery<T>(
                "dbo.PagedQuery @tblName,@fldName,@pageSize,@page,@fldSort,@strCondition,@pageCount out,@counts out,@strSql out",
                paras.ToArray()).ToList();
            total = countParameter.Value == DBNull.Value ? 0 : Convert.ToInt32(countParameter.Value);
            return ret;
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed && disposing)
            {
                _entities.Dispose();
            }
            _disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

 

2. 具体类继承泛型类

namespace Crm.Data.Logic.Logic
{
    public class CrmDispatchLogic:AbstractRepository<LifeEntities,Crm_Dispatch>
    {
        
    }
}

 

3. 使用具体类

var dispatchSvc = new CrmDispatchLogic();
        var dispatchModel = dispatchSvc.GetAll().FirstOrDefault(m => m.Handler == opId
            && m.IsUse == 1);
        if (dispatchModel != null)
        {}

转载于:https://www.cnblogs.com/itjeff/p/5552648.html

相关文章:

  • MongoDB 是如何鼓励和激励开发者社区的
  • dubbo源码分析系列——dubbo的SPI机制源码分析
  • Elasticsearch数据建模-关联查询
  • Ubuntu/Linux 笔记应用 为知笔记(支持markdown)
  • 使用weave实现跨主机docker容器互联
  • 怎么打开Office 2007 Excel加密文档
  • mysql 慢查询分析工具:pt-query-digest 在mac 上的安装使用 ...
  • Unity3D 之3D游戏角色控制器运动
  • linux下smb文件共享服务器详解
  • 几何画板中作函数图像的几种方法
  • HighCharts 详细使用及API文档说明
  • HTML最新标准HTML5小结
  • Docker的镜像、容器和仓库
  • 互联网
  • iOS开发--利用MPMoviePlayerViewController播放视频简单实现
  • 《Javascript数据结构和算法》笔记-「字典和散列表」
  • 【Redis学习笔记】2018-06-28 redis命令源码学习1
  • 【跃迁之路】【463天】刻意练习系列222(2018.05.14)
  • 03Go 类型总结
  • 10个确保微服务与容器安全的最佳实践
  • 345-反转字符串中的元音字母
  • 78. Subsets
  • JavaScript类型识别
  • markdown编辑器简评
  • mockjs让前端开发独立于后端
  • oschina
  • PermissionScope Swift4 兼容问题
  • tensorflow学习笔记3——MNIST应用篇
  • 阿里云应用高可用服务公测发布
  • 基于Mobx的多页面小程序的全局共享状态管理实践
  • 解决iview多表头动态更改列元素发生的错误
  • 开发基于以太坊智能合约的DApp
  • 开源SQL-on-Hadoop系统一览
  • 聊聊sentinel的DegradeSlot
  • 那些被忽略的 JavaScript 数组方法细节
  • 深度学习入门:10门免费线上课程推荐
  • 无服务器化是企业 IT 架构的未来吗?
  • 小程序开发中的那些坑
  • Spark2.4.0源码分析之WorldCount 默认shuffling并行度为200(九) ...
  • # Pytorch 中可以直接调用的Loss Functions总结:
  • #我与Java虚拟机的故事#连载09:面试大厂逃不过的JVM
  • (10)STL算法之搜索(二) 二分查找
  • (初研) Sentence-embedding fine-tune notebook
  • (附源码)springboot 校园学生兼职系统 毕业设计 742122
  • (三)模仿学习-Action数据的模仿
  • (三分钟了解debug)SLAM研究方向-Debug总结
  • (十) 初识 Docker file
  • (一)Spring Cloud 直击微服务作用、架构应用、hystrix降级
  • .NET CORE使用Redis分布式锁续命(续期)问题
  • .NET 自定义中间件 判断是否存在 AllowAnonymousAttribute 特性 来判断是否需要身份验证
  • .NET连接MongoDB数据库实例教程
  • .net最好用的JSON类Newtonsoft.Json获取多级数据SelectToken
  • @ModelAttribute使用详解
  • [202209]mysql8.0 双主集群搭建 亲测可用
  • [bbk5179]第66集 第7章 - 数据库的维护 03