EF RepositoryBase 参考示例【转】
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 参考示例【转】的更多相关文章
- JavaEE参考示例 SpringSide 4.0 GA版杀青
SpringSide是以Spring Framework为核心的,Pragmatic风格的JavaEE应用参考示例,是JavaEE世界中的主流技术选型,较佳实践的总结与演示. 经过漫长的7个月和6个R ...
- 搜索应用参考示例XXL-SEARCH
<搜索应用参考示例XXL-SEARCH> 一.简介 1.1 概述 XXL-SEARCH 是以 "lucene/elasticsearch" 为核心的,Pragmatic ...
- Oracle数据库用EF操作的示例
Using EF Oracle Sample Provider with EDM Designer (from msdn) Many people are asking if it is possi ...
- DHTMLX地图开发参考示例摘录
1.新建地图:http://www.dhtmlx.com/docs/products/dhtmlxLayout/samples/04_components/12_gmaps.html 2.地图框架效果 ...
- as3.0服务端FMS软件常用的方法与属性参考示例
转自:http://www.cuplayer.com/player/PlayerCode/RTMP/2012/0918429.html Application类的方法汇总方法 描述Applicatio ...
- Nginx配置参数详解参考示例
user nobody; worker_processes 2; events{ worker_connections 1024; } http{ #设置默认类型为二进制流 default_type ...
- socket.io入门示例参考
参考示例地址:http://www.linchaoqun.com/html/cms/content.jsp?menu=nodejs&id=1480081169735
- 推荐几篇关于EF的好文章
文章作者 Julie Lerman 是 Microsoft MVP..NET 导师和顾问,住在佛蒙特州的山区.您可以在全球的用户组和会议中看到她对数据访问和其他 .NET 主题的演示.她的博客地址是 ...
- EasyUI+MVC+EF简单用户管理Demo(问题及解决)
写在前面 iframe-src EntityFramework版本 connectionStrings View.Action.页面跳转 EasyUI中DataGrid绑定 新增.修改和删除数据 效果 ...
随机推荐
- 【7】了解Bootstrap栅格系统基础案例(2)
ps.这一次要说的是“Responsive column resets”,但是不知道为什么中文官网没有给出翻译,但是在看到案例的时候,感觉这就像一个bug,我自己姑且叫这个是一个高度bug吧,方便自己 ...
- 机器学习实战:数据预处理之独热编码(One-Hot Encoding)
问题由来 在很多机器学习任务中,特征并不总是连续值,而有可能是分类值. 例如,考虑一下的三个特征: ["male", "female"] ["from ...
- .Net 平台下的互联网架构新思考
上一篇<互联网应用架构谈>有很多阅读量,但后来实践中发现基于WCF服务层技术用于实现网站访问的效率是有问题的. 我的本意是以WCF中间层解决商业逻辑,供各个平台调用,然而还是带来诸多的麻烦 ...
- hdu 3591 The trouble of Xiaoqian
hdu 3591 The trouble of Xiaoqian 题意:xiaoqi要买一个T元的东西,当前的货币有N种,xiaoqi对于每种货币有Ci个:题中定义了最小数量即xiaoqi拿去买东西 ...
- Codeforces 616E - Sum of Remainders
616E Sum of Remainders Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + - + n mod m. As ...
- uCGUI窗口重绘代码分析
一.概述 µC/GUI的窗口重绘是学习者理解窗口工作原理和应用窗口操作的重点.µC/GUI的窗口重绘引入了回调机制,回调机制可以实现图形系统调用用户的代码,由于图形系统使用了剪切算法,使得屏幕重绘的效 ...
- 【c3p0】目前使用它的开源项目有Hibernate,Spring等
C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展.目前使用它的开源项目有Hibernate,Spring等. c3p0与dbcp区别 JNDI ...
- hdu 3303 Harmony Forever (线段树 + 抽屉原理)
http://acm.hdu.edu.cn/showproblem.php?pid=3303 Harmony Forever Time Limit: 20000/10000 MS (Java/Othe ...
- CSS的绝对定位和相对定位
css定位标签position包括两个值:relative(相对定位)和absolute(绝对定位),position样式一般都是和top.bottom.left.right一起使用来确定一个标签的位 ...
- JDBC之PreparedStatement模糊查询
今天要做一个关于模糊查询的需求,以前用JDBC做精确查询都是用 "SELECT * FROM test WHERE id = ?",所以用模糊查询时理所当然的也用了"SE ...