博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
EF 增删改查 泛型方法、类
阅读量:6951 次
发布时间:2019-06-27

本文共 5386 字,大约阅读时间需要 17 分钟。

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)
        {}

转载地址:http://ukuil.baihongyu.com/

你可能感兴趣的文章
《Web前端工程师修炼之道(原书第4版)》——互联网与Web
查看>>
《应用时间序列分析:R软件陪同》——2.11 习题
查看>>
C++工厂方法模式
查看>>
举例说明jquery插件的编写方法
查看>>
英特尔逆天原型机:在 Android 上跑 Debian
查看>>
区块链+”来了,区块链金融将如何颠覆传统金融
查看>>
Perl 语言流行度处于历史最低点
查看>>
Apache Qpid Proton 0.16.0,轻量通信库
查看>>
《Adobe Premiere Pro CC经典教程(彩色版)》——第2课 设置项目 2.1 开始
查看>>
将 iOS 软件移植到 Windows 10 的桥梁将很快打通
查看>>
《高度安全环境下的高级渗透测试》—第1章1.5节安装OpenOffice
查看>>
中国互联网今日正式满 20 岁
查看>>
《I'm a Mac:雄狮训练手册》——2.3 账户类型
查看>>
《Arduino开发实战指南:机器人卷》一1.3 安装Arduino Uno驱动
查看>>
redis持久化(persistence)
查看>>
《Pig编程指南》一导读
查看>>
《智能家居产品 从设计到运营》——2.2 智能设备的触角:传感器
查看>>
Lua学习小记——语言
查看>>
《R数据可视化手册》——2.5 绘制箱线图
查看>>
互联网企业安全高级指南3.7 如何看待SDL
查看>>