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. 控制 WAP 网站上输入框的默认类型

    比如手机号,卡输入框应该默认显示数字键盘,邮箱输入框应该默认显示邮箱键盘.www . c s d n 1 2 3 . com/html/itweb/20130802/36036_36043_36004 ...

  2. smarty模板的基础搭建

    1.下载smarty模板,官方即有 2.解压即可.你会得这样的目录 除了libs文件夹其余都可以删掉(不知道有啥用). 3.在当前目录下分别创建templates.templates_c.cache. ...

  3. 现代php开发

    最近在看 Modern PHP 很薄的一本书,有种发现新大陆的感觉,强烈推荐.php是一门脚本语言,随着web的发展而发展起来,最早的时候大家还是混编html,php,完全没有工程项目的概念,(我们公 ...

  4. windows 系统下,小数据量Oracle用户物理备份

    环境:windows Server 2003 oracle 10g,系统间备份 目标系统创建共享文件,原系统挂载共享目录 写批处理脚本,用任务计划定时调用 Rem * 由于系统实时性要求不是很高,数据 ...

  5. Linux_Struct file()结构体

    struct file结构体定义在/linux/include/linux/fs.h(Linux 2.6.11内核)中,其原型是:struct file {        /*         * f ...

  6. Anagrams问题

    #include<stdio.h> #include<string.h> int main() { int i; ],word2[]; //分别用于存储输入的两个单词 int ...

  7. CODEVS 1004四子连棋

    [题目描述 Description] 在一个4*4的棋盘上摆放了14颗棋子,其中有7颗白色棋子,7颗黑色棋子,有两个空白地带,任何一颗黑白棋子都可以向上下左右四个方向移动到相邻的空格,这叫行棋一步,黑 ...

  8. git 提交

    git rebase -i 在使用git开发的时候经常会面临一个常见的问题.多个commit 需要合并为一个完整的commit提交. 合并多个commit为一个完整的commit 我先基于develo ...

  9. <一> ASP.NET Html 表单

    把客户端数据发送到服务器端用<form>标签 htmlpage.html Default2.aspx.cs

  10. iOS上绘制自然的签名-b

    这里有一篇很棒的文章写如何在Android上获取流畅的签名:Smoother Signatures:https://corner.squareup.com/2012/07/smoother-signa ...