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,然后使用母版页 ...
随机推荐
- Hello World! 2010年山东省第一届ACM大学生程序设计竞赛
Hello World! Time Limit: 1000MS Memory limit: 65536K 题目描述 We know that Ivan gives Saya three problem ...
- Java 的布局管理器GridBagLayout的使用方法(转)
GridBagLayout是java里面最重要的布局管理器之一,可以做出很复杂的布局,可以说GridBagLayout是必须要学好的的, GridBagLayout 类是一个灵活的布局管理器,它不要求 ...
- iOS_11_tableViewCell使用alertView变更数据
最后效果图: Girl.h // // Girl.h // 11_tableView的使用_红楼梦 // // Created by beyond on 14-7-26. // Copyright ( ...
- tolower (Function)
this is a function that Convert uppercase letter to lowercase Converts c to its lowercase equivalent ...
- HTML的标签使用
<p>段落标签</p>:段落标签 <hx>标题标签</hx>:标题标签,x代表1-6 <em>斜体</em>:显示的字体是斜的 ...
- Eclipse热键
Eclipse编辑功能很强大.掌握Eclipse快捷功能.高开发效率.Eclipse中有例如以下一些和编辑相关的快捷键. 1. [ALT+/] 此快捷键为用户编辑的好帮手.能为用户提供 ...
- AndroidUI的组成部分ProgressBar
package com.gc.progressbar; /* * 1.ProgressBar组件也是一组重要的组件,ProgressBar本身代表了进度条组件, * 它还派生了两个经常使用的组件:Se ...
- 如何使用SQLite数据库 匹配一个字符串的子串?
select * from table_name where 字符串 like '%'||列名||'%'
- Linux互斥和同步应用程序(四):posix互斥信号和同步
[版权声明:尊重原创.转载请保留源:blog.csdn.net/shallnet 要么 .../gentleliu,文章仅供学习交流,请勿用于商业用途] 在前面讲共享内 ...
- oracle 打开trace,并分析trace
SQL> oradebug event 10046 trace name context forever,level 8 ORA-00072: process "Unix proces ...