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

EF RepositoryBase 参考示例【转】的更多相关文章

  1. JavaEE参考示例 SpringSide 4.0 GA版杀青

    SpringSide是以Spring Framework为核心的,Pragmatic风格的JavaEE应用参考示例,是JavaEE世界中的主流技术选型,较佳实践的总结与演示. 经过漫长的7个月和6个R ...

  2. 搜索应用参考示例XXL-SEARCH

    <搜索应用参考示例XXL-SEARCH> 一.简介 1.1 概述 XXL-SEARCH 是以 "lucene/elasticsearch" 为核心的,Pragmatic ...

  3. Oracle数据库用EF操作的示例

    Using EF Oracle Sample Provider with EDM Designer  (from msdn) Many people are asking if it is possi ...

  4. DHTMLX地图开发参考示例摘录

    1.新建地图:http://www.dhtmlx.com/docs/products/dhtmlxLayout/samples/04_components/12_gmaps.html 2.地图框架效果 ...

  5. as3.0服务端FMS软件常用的方法与属性参考示例

    转自:http://www.cuplayer.com/player/PlayerCode/RTMP/2012/0918429.html Application类的方法汇总方法 描述Applicatio ...

  6. Nginx配置参数详解参考示例

    user nobody; worker_processes 2; events{ worker_connections 1024; } http{ #设置默认类型为二进制流 default_type ...

  7. socket.io入门示例参考

    参考示例地址:http://www.linchaoqun.com/html/cms/content.jsp?menu=nodejs&id=1480081169735

  8. 推荐几篇关于EF的好文章

    文章作者 Julie Lerman 是 Microsoft MVP..NET 导师和顾问,住在佛蒙特州的山区.您可以在全球的用户组和会议中看到她对数据访问和其他 .NET 主题的演示.她的博客地址是 ...

  9. EasyUI+MVC+EF简单用户管理Demo(问题及解决)

    写在前面 iframe-src EntityFramework版本 connectionStrings View.Action.页面跳转 EasyUI中DataGrid绑定 新增.修改和删除数据 效果 ...

随机推荐

  1. configure: error: zlib library and headers are required

    configure: error: zlib library and headers are required (1)直接看是zlib没安装导致的,yum list |grep zlib* 看到的是全 ...

  2. WPF学习笔记2——XAML之2

    三.事件处理程序与代码隐藏 例如,为一个Page添加一个Button控件,并为该Button添加事件名称Button_Click: <Page xmlns="http://schema ...

  3. Socket和SignalR

    写到一半停电了,这心情真是哔了狗了,草稿箱竟然也没有!!! 好吧,这篇文档是之前写的记录,现在来完善(还是要完善的). 导读: 附件代码实现: Socket: 定义,同步实现,异步实现,还包括了TCP ...

  4. hdu 3746 Cyclic Nacklace KMP循环节

    Cyclic Nacklace 题意:给一个长度为Len( 3 <= Len <= 100000 )的英文串,问你在字符串后面最少添加几个字符可以使得添加后的串为周期串? Sample I ...

  5. 树莓派 raspberry 入门之安装操作系统以及配置

    最近新入手一树莓派,型号是2代B,屏幕是微雪的7 inch c型 显示屏.下面来教大家怎么点亮树莓派. 第一步,装好显示器,显示器的电源接在树莓派的usb口上,HDMI口不多说,连上.然后装好鼠标.键 ...

  6. Oracle分析函数之LEAD和LAG

    LAG 访问结果集中当前行之前的行 LAG (value_expr [,offset] [,default])OVER ( [ partition_by_clause ] order_by_claus ...

  7. javascript 通用loading动画效果

    由于项目中多处要给ajax提交的时候增加等待动画效果,所以就写了一个简单的通用js方法: 代码如下: /*ajax提交的延时等待效果*/ var AjaxLoding = new Object(); ...

  8. Linux和Windows下查看环境变量方法对比

    摘自:Linux和Windows下查看环境变量方法对比 一.查看所有环境变量的名称和值 Linux下:export Windows下:set 二.根据名称查该环境变量的值 Linux下:echo $环 ...

  9. SDC(1)–Hold Time

    从以下两个论点触发可能会使Hold Time的计算理解起来更加容易: (1) H = SU – 1 ; (2) Hold Check的目的是确保Source Clock在某个边沿打出数据时,该数据不会 ...

  10. cxf2.4.3中jaxb-api.jar、jaxws-api.jar与jdk1.6.0_02不兼容问题

    http://chxiaowu.iteye.com/blog/1243475 Exception in thread "main" java.lang.NoClassDefFoun ...