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)
{}
EF 增删改查 泛型方法、类的更多相关文章
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(5)-EF增删改查by糟糕的代码
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(5)-EF增删改查by糟糕的代码 上一讲我们创建了一系列的解决方案,我们通过一个例子来看看层与层之间的关系 ...
- WPF MVVM+EF增删改查 简单示例(二) 1对1 映射
WPF MVVM+EF增删改查 简单示例(一)实现了对学生信息的管理. 现在需求发生变更,在录入学生资料的时候同时需要录入学生的图片信息,并且一名学生只能有一张图片资料.并可对学生的图片资料进行更新. ...
- 分享一个自己写的MVC+EF “增删改查” 无刷新分页程序
分享一个自己写的MVC+EF “增删改查” 无刷新分页程序 一.项目之前得添加几个组件artDialog.MVCPager.kindeditor-4.0.先上几个效果图. 1.首先建立一个数 ...
- C# EF增删改查
1.增 //1.创建一个EF数据上下文对象 MyDBEntities context=new MyDBEntities(); //2.将要添加的数据,封装成对象 Users user = new Us ...
- MVC3.0 EF增删改查的封装类
本人亲身使用EF CodeFirst,因为增删改查都是使用EF内置的一些方法,我想把它封装到一个类调用就行了.结合网上的资料和自己的整理,若有不对的地方望斧正,感激不尽.直接上代码吧.我就用新闻的增删 ...
- EF学习笔记-1 EF增删改查
首次接触Entity FrameWork,就感觉非常棒.它节省了我们以前写SQL语句的过程,同时也让我们更加的理解面向对象的编程思想.最近学习了EF的增删改查的过程,下面给大家分享使用EF对增删改查时 ...
- EF增删改查的优化
在EF的上一篇博客中已经对它的增删改查有了一个简单的了解.当中的改动过程是先要把要改动的内容查出来然后再进行改动.保存.它详细的过程是这种 首先当在运行查询语句的时候"EF数据上下文&quo ...
- ef增删改查
[C#]Entity Framework 增删改查和事务操作 1.增加对象 DbEntity db = new DbEntity(); //创建对象实体,注意,这里需要对所有属性进行赋值(除了自动增长 ...
- ASP.NET中使用Entity Framework开发增删改查的Demo(EF增删改查+母版页的使用)
这里更多的是当作随身笔记使用,记录一下学到的知识,以便淡忘的时候能快速回顾 这里是该项目的第二部分, 第一部分 第二部分(当前部分) 大完结版本 此Demo是新建了一个音乐类型的web,然后使用母版页 ...
随机推荐
- 在基于阿里云serverCentOS6.5下安装Subversion 1.6.5服务
近期阿里云搞了个1元免费提供云server的活动,偶心痒痒就申请了一个. 正好能够作为团队的SVNserver了,以下就来部署SVN服务吧. 一.安装基础环境 apr-1.5.0.tar.gz apr ...
- Thinkphp编辑器扩展类kindeditor用法
一, 使用前的准备. 使用前请确认你已经建立好了一个Thinkphp站点项目. 1,Keditor.class.php和JSON.class.php 是编辑器扩展类文件,将他们拷贝到你的站点项目的Th ...
- 一份关于jvm内存调优及原理的学习笔记
JVM 一.虚拟机的基本结构 1.jvm整体架构 类加载子系统:负责从文件系统或者网络中加载class信息,存入方法区中. 方法区(Perm):存放加载后的class信息,包括静态方法,jdk1.6以 ...
- spring mvc 错误摘要--。位。
1....identifier of an instance of org.szgzw.ent.profile.baseinfo.enterprise.EnterpriseEntity was alt ...
- NFS 配置服务
NFS 配置服务 北京市海淀区 张俊浩 一.NFS.即网络文件系统(Network File System,NFS).一种使用于分散式文件系统的协议,由升阳公司开发.于1984年向外发布.功能是通过 ...
- 用SourceTree轻巧Git项目图解
用SourceTree轻松Git项目图解 这篇文档的目的是:让使用Git更轻松. 看完这篇文档你能做到的是: 1.简单的用Git管理项目. 2.怎样既要开发又要处理发布出去的版本bug情况. Sour ...
- nyoj 7 街区最短路径问题 【数学】
找出横纵坐标的中位数,怎么找:先对x排序找x的中位数x0,再对y排序找y的中位数y0:最后统计各点到中位数点(x0, y0)的总距离: 街区最短路径问题 时间限制:3000 ms | 内存限制:6 ...
- UVa 11587 - Brick Game
称号:背景:brick game有N块,给你一个整数的定数S,两个人轮流木: 的木块数是集合S中存在的随意数字.取走最后木块的人获胜.无法取则对方获胜. 题干:如今让你先取,给你一个你的结果序列串T, ...
- C++学习笔记25,析构函数总是会宣布virtual
为了永远记住析构函数声明virtual----><<effective c++>> 为这句话不一定对,但无需质疑的是这句话是非常实用的. 查看以下的样例: #includ ...
- rabbitmq技术的一些感悟(一)
Rabbitmq 初识rabbitmq RabbitMQ是流行的开源消息队列系统,用erlang语言开发.RabbitMQ是AMQP(高级消息队列协议)的标准实现.假设不熟悉AMQP,直接看Rabbi ...