public class BaseDAL
{
string strConn = "";
public BaseDAL(string connString)
{
strConn = connString;
} #region 通用增删改查
#region 非原始sql语句方式
/// <summary>
/// 新增
/// </summary>
/// <param name="entity">实体</param>
/// <returns>返回受影响行数</returns>
public bool Add<T>(T entity) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
db.Entry<T>(entity).State = EntityState.Added;
return db.SaveChanges() > 0;
}
} /// <summary>
/// 改动
/// </summary>
/// <param name="entity">实体</param>
/// <returns>返回受影响行数</returns>
public bool Update<T>(T entity) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
db.Set<T>().Attach(entity);
db.Entry<T>(entity).State = EntityState.Modified;
return db.SaveChanges() > 0;
}
} /// <summary>
/// 删除
/// </summary>
/// <param name="entity">实体</param>
/// <returns>返回受影响行数</returns>
public bool Delete<T>(T entity) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
db.Set<T>().Attach(entity);
db.Entry<T>(entity).State = EntityState.Deleted;
return db.SaveChanges() > 0;
}
} /// <summary>
/// 依据条件删除
/// </summary>
/// <param name="deleWhere">删除条件</param>
/// <returns>返回受影响行数</returns>
public bool DeleteByConditon<T>(Expression<Func<T, bool>> deleWhere) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
List<T> entitys = db.Set<T>().Where(deleWhere).ToList();
entitys.ForEach(m => db.Entry<T>(m).State = EntityState.Deleted);
return db.SaveChanges() > 0;
}
} /// <summary>
/// 查找单个
/// </summary>
/// <param name="id">主键</param>
/// <returns></returns>
public T GetSingleById<T>(int id) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
return db.Set<T>().Find(id);
}
} /// <summary>
/// 查找单个
/// </summary>
/// <param name="seleWhere">查询条件</param>
/// <returns></returns>
public T GetSingle<T>(Expression<Func<T, bool>> seleWhere) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
return db.Set<T>().AsExpandable().FirstOrDefault(seleWhere);
}
} /// <summary>
/// 获取全部实体集合
/// </summary>
/// <returns></returns>
public List<T> GetAll<T>() where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
return db.Set<T>().AsExpandable().ToList<T>();
}
} /// <summary>
/// 获取全部实体集合(单个排序)
/// </summary>
/// <returns></returns>
public List<T> GetAll<T, Tkey>(Expression<Func<T, Tkey>> orderWhere, bool isDesc) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
return CommonSort(db.Set<T>().AsExpandable(), orderWhere, isDesc).ToList<T>();
}
} /// <summary>
/// 获取全部实体集合(多个排序)
/// </summary>
/// <returns></returns>
public List<T> GetAll<T>(params OrderModelField[] orderByExpression) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
return CommonSort(db.Set<T>().AsExpandable(), orderByExpression).ToList();
}
} /// <summary>
/// 单个排序通用方法
/// </summary>
/// <typeparam name="Tkey">排序字段</typeparam>
/// <param name="data">要排序的数据</param>
/// <param name="orderWhere">排序条件</param>
/// <param name="isDesc">是否倒序</param>
/// <returns>排序后的集合</returns>
public IQueryable<T> CommonSort<T, Tkey>(IQueryable<T> data, Expression<Func<T, Tkey>> orderWhere, bool isDesc) where T : class
{
if (isDesc)
{
return data.OrderByDescending(orderWhere);
}
else
{
return data.OrderBy(orderWhere);
}
} /// <summary>
/// 多个排序通用方法
/// </summary>
/// <typeparam name="Tkey">排序字段</typeparam>
/// <param name="data">要排序的数据</param>
/// <param name="orderWhereAndIsDesc">字典集合(排序条件,是否倒序)</param>
/// <returns>排序后的集合</returns>
public IQueryable<T> CommonSort<T>(IQueryable<T> data, params OrderModelField[] orderByExpression) where T : class
{
//创建表达式变量參数
var parameter = Expression.Parameter(typeof(T), "o"); if (orderByExpression != null && orderByExpression.Length > 0)
{
for (int i = 0; i < orderByExpression.Length; i++)
{
//依据属性名获取属性
var property = typeof(T).GetProperty(orderByExpression[i].PropertyName);
//创建一个訪问属性的表达式
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter); string OrderName = "";
if (i > 0)
{
OrderName = orderByExpression[i].IsDESC ? "ThenByDescending" : "ThenBy";
}
else
OrderName = orderByExpression[i].IsDESC ? "OrderByDescending" : "OrderBy"; MethodCallExpression resultExp = Expression.Call(typeof(Queryable), OrderName, new Type[] { typeof(T), property.PropertyType },
data.Expression, Expression.Quote(orderByExp)); data = data.Provider.CreateQuery<T>(resultExp);
}
}
return data;
} /// <summary>
/// 依据条件查询实体集合
/// </summary>
/// <param name="seleWhere">查询条件 lambel表达式</param>
/// <returns></returns>
public List<T> GetList<T>(Expression<Func<T, bool>> seleWhere) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
return db.Set<T>().AsExpandable().Where(seleWhere).ToList();
}
} /// <summary>
/// 依据条件查询实体集合
/// </summary>
/// <param name="seleWhere">查询条件 lambel表达式</param>
/// <returns></returns>
public List<T> GetList<T, TValue>(Expression<Func<T, TValue>> seleWhere, IEnumerable<TValue> conditions) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{ return db.Set<T>().AsExpandable().WhereIn<T, TValue>(seleWhere, conditions).ToList();
}
} /// <summary>
/// 依据条件查询实体集合(单个字段排序)
/// </summary>
/// <param name="seleWhere">查询条件 lambel表达式</param>
/// <returns></returns>
public List<T> GetList<T, Tkey>(Expression<Func<T, bool>> seleWhere, Expression<Func<T, Tkey>> orderWhere, bool isDesc) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
return CommonSort(db.Set<T>().AsExpandable().Where(seleWhere), orderWhere, isDesc).ToList();
}
} /// <summary>
/// 依据条件查询实体集合(多个字段排序)
/// </summary>
/// <param name="seleWhere">查询条件 lambel表达式</param>
/// <returns></returns>
public List<T> GetList<T>(Expression<Func<T, bool>> seleWhere, params OrderModelField[] orderByExpression) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
return CommonSort(db.Set<T>().AsExpandable().Where(seleWhere), orderByExpression).ToList();
}
} /// <summary>
/// 获取分页集合(无条件无排序)
/// </summary>
/// <returns></returns>
public List<T> GetListPaged<T, Tkey>(int pageIndex, int pageSize, out int totalcount) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
totalcount = db.Set<T>().AsExpandable().Count();//获取总数
//须要添加AsExpandable(),否则查询的是全部数据到内存,然后再排序 AsExpandable是linqkit.dll中的方法
return db.Set<T>().AsExpandable().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
} /// <summary>
/// 获取分页集合(无条件单个排序)
/// </summary>
/// <returns></returns>
public List<T> GetListPaged<T, Tkey>(int pageIndex, int pageSize, Expression<Func<T, Tkey>> orderWhere, bool isDesc, out int totalcount) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
totalcount = db.Set<T>().AsExpandable().Count();//获取总数
//须要添加AsExpandable(),否则查询的是全部数据到内存。然后再排序 AsExpandable是linqkit.dll中的方法
return CommonSort(db.Set<T>().AsExpandable(), orderWhere, isDesc).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
} /// <summary>
/// 获取分页集合(无条件多字段排序)
/// </summary>
/// <returns></returns>
public List<T> GetListPaged<T>(int pageIndex, int pageSize, out int totalcount, params OrderModelField[] orderByExpression) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
totalcount = db.Set<T>().AsExpandable().Count();//获取总数
//须要添加AsExpandable(),否则查询的是全部数据到内存,然后再排序 AsExpandable是linqkit.dll中的方法
return CommonSort(db.Set<T>().AsExpandable(), orderByExpression).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
} /// <summary>
/// 获取分页集合(有条件无排序)
/// </summary>
/// <returns></returns>
public List<T> GetListPaged<T, Tkey>(int pageIndex, int pageSize, Expression<Func<T, bool>> seleWhere, out int totalcount) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
totalcount = db.Set<T>().AsExpandable().Where(seleWhere).Count();//获取总数
//须要添加AsExpandable(),否则查询的是全部数据到内存。然后再排序 AsExpandable是linqkit.dll中的方法
return db.Set<T>().AsExpandable().Where(seleWhere).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
} /// <summary>
/// 获取分页集合(有条件单个排序)
/// </summary>
/// <returns></returns>
public List<T> GetListPaged<T, Tkey>(int pageIndex, int pageSize, Expression<Func<T, bool>> seleWhere,
Expression<Func<T, Tkey>> orderWhere, bool isDesc, out int totalcount) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
totalcount = db.Set<T>().AsExpandable().Where(seleWhere).Count();//获取总数
//须要添加AsExpandable(),否则查询的是全部数据到内存。然后再排序 AsExpandable是linqkit.dll中的方法
return CommonSort(db.Set<T>().AsExpandable().Where(seleWhere), orderWhere, isDesc).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
} /// <summary>
/// 获取分页集合(有条件多字段排序)
/// </summary>
/// <returns></returns>
public List<T> GetListPaged<T>(int pageIndex, int pageSize, Expression<Func<T, bool>> seleWhere,
out int totalcount, params OrderModelField[] orderModelFiled) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
totalcount = db.Set<T>().AsExpandable().Where(seleWhere).Count();//获取总数
//须要添加AsExpandable(),否则查询的是全部数据到内存,然后再排序 AsExpandable是linqkit.dll中的方法
return CommonSort(db.Set<T>().AsExpandable().Where(seleWhere), orderModelFiled).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
}
#endregion #region 原始sql操作
/// <summary>
/// 运行操作
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
public void ExecuteSql(string sql, params object[] paras)
{
using (SysDb db = new SysDb(strConn))
{
db.Database.ExecuteSqlCommand(sql, paras);
}
} /// <summary>
/// 查询列表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <returns></returns>
public List<T> QueryList<T>(string sql, params object[] paras) where T : class
{
using (SysDb db = new SysDb(strConn))
{
return db.Database.SqlQuery<T>(sql, paras).ToList();
}
} /// <summary>
/// 查询单个
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <returns></returns>
public T QuerySingle<T>(string sql, params object[] paras) where T : class
{
using (SysDb<T> db = new SysDb<T>(strConn))
{
return db.Database.SqlQuery<T>(sql, paras).FirstOrDefault();
}
} /// <summary>
/// 运行事务
/// </summary>
/// <param name="lsSql"></param>
/// <param name="lsParas"></param>
public void ExecuteTransaction(List<String> lsSql, List<Object[]> lsParas)
{
using (SysDb db = new SysDb(strConn))
{
using (var tran = db.Database.BeginTransaction())
{
try
{
for (int i = 0; i < lsSql.Count; i++)
{
if (lsParas != null && lsParas.Count > 0)
{
db.Database.ExecuteSqlCommand(lsSql[i], lsParas[i]);
}
}
foreach (String item in lsSql)
{
db.Database.ExecuteSqlCommand(item);
} tran.Commit();
}
catch (Exception ex)
{
tran.Rollback();
throw ex;
}
}
}
}
#endregion
#endregion #region 通用属性
/// <summary>
/// 获取数据库server当前时间。
/// </summary>
public DateTime ServerTime
{
get
{
using (SysDb db = new SysDb(strConn))
{
String sql = "SELECT GETDATE()";
Object objServerTime = db.Database.SqlQuery<Object>(sql);
return Convert.ToDateTime(objServerTime);
}
}
} /// <summary>
/// 获取数据库版本号。
/// </summary>
public String DatabaseVersion
{
get
{
using (SysDb db = new SysDb(strConn))
{
try
{
String sql = "SELECT Version FROM Sys_Version";
Object objServerTime = db.Database.SqlQuery<Object>(sql);
return Convert.ToString(objServerTime);
}
catch
{
}
return String.Empty;
}
}
}
#endregion }
public static class QueryableExtension
{
/// <summary>
/// 扩展方法 支持 in 操作
/// </summary>
/// <typeparam name="TEntity">须要扩展的对象类型</typeparam>
/// <typeparam name="TValue">in 的值类型</typeparam>
/// <param name="source">须要扩展的对象</param>
/// <param name="valueSelector">值选择器 比如c=>c.UserId</param>
/// <param name="values">值集合</param>
/// <returns></returns>
public static IQueryable<TEntity> WhereIn<TEntity, TValue>(this IQueryable<TEntity> source, Expression<Func<TEntity, TValue>> valueSelector,
IEnumerable<TValue> values)
{
if (null == valueSelector) { throw new ArgumentNullException("valueSelector"); }
if (null == values) { throw new ArgumentNullException("values"); }
ParameterExpression p = valueSelector.Parameters.Single(); if (!values.Any())
{
return source;
}
var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));
var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));
return source.Where(Expression.Lambda<Func<TEntity, bool>>(body, p));
}
}
public struct OrderModelField
{ public bool IsDESC { get; set; }
public string PropertyName { get; set; }
}

dbcontext类:

    public class SysDb : DbContext
{
bool isNew = true;//是否是新的sql运行
string strMsg = "";//sql运行的相关信息
string strConn = "";//数据库连接字符串
string UserName = "";//日志username称
string AdditionalInfo = "";//日志额外信息
public SysDb(string connString) : // 数据库链接字符串
base(connString)
{
strConn = connString;
Database.SetInitializer<SysDb>(null);//设置为空,防止自己主动检查和生成
base.Database.Log = (info) => Debug.WriteLine(info);
} public SysDb(string connString, string logUserName, string logAdditionalInfo) : // 数据库链接字符串
base(connString)
{
strConn = connString;
Database.SetInitializer<SysDb>(null);//设置为空,防止自己主动检查和生成
UserName = logUserName;
AdditionalInfo = logAdditionalInfo;
base.Database.Log = AddLogger;
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//去掉复数映射
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
} /// <summary>
/// 加入日志
/// </summary>
/// <param name="info"></param>
public void AddLogger(string info)
{
if (info != "\r\n" && (!info.Contains("Sys_EventLog")))
{
string strTemp = info.ToUpper().Trim();
if (isNew)
{
//记录增删改
if (strTemp.StartsWith("INSERT") || strTemp.StartsWith("UPDATE") || strTemp.StartsWith("DELETE"))
{
strMsg = info;
isNew = false;
}
}
else
{
if (strTemp.StartsWith("CLOSED CONNECTION"))
{
//添加新日志
using (SysDb db = new SysDb(strConn))
{
try
{
//保存日志到数据库或其它地方 }
catch (Exception ex)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "//logError.txt"))
{
sw.Write(ex.Message);
sw.Flush();
}
}
}
//清空
strMsg = "";
isNew = true;
}
else
{
strMsg += info;
}
} }
} }
public class SysDb<T> : SysDb where T : class
{
public SysDb(string connString) : // 数据库链接字符串
base(connString)
{
Database.SetInitializer<SysDb<T>>(null);//设置为空。防止自己主动检查和生成
} public SysDb(string connString, string logUserName, string logAdditionalInfo) : // 数据库链接字符串
base(connString,logUserName,logAdditionalInfo)
{
Database.SetInitializer<SysDb<T>>(null);//设置为空。防止自己主动检查和生成
} public DbSet<T> Entities { get; set; }
}

界面使用:(bll层忽略)

 public class BusinessController : Controller
{
//
// GET: /Jygl/Business/
BaseBLL basebll = new BaseBLL(WebHelper.Conn); public ActionResult GetXMList(int page,int rows)
{
int count = 0;
//查询条件
//Expression<Func<JY_XM, bool>> searchPredicate = PredicateBuilder.True<JY_XM>();
//searchPredicate = searchPredicate.And(c => c.UserName.Contains(""));
Expression<Func<JY_XM, int>> keySelector = u => u.UID;
string str = ExceptionHelper<JY_XM>.TryCatchPageQueryJson<int>(basebll.GetListPaged, page, rows, keySelector, false, out count);
return Content(str);
} [HttpPost]
public ActionResult XMEdit(JY_XM jyxm)
{
basebll.Add(jyxm);
return View();
} public ActionResult GetAllGCLB()
{ List<DICT_GCLB> lsGCLB = basebll.GetAll<DICT_GCLB>();
DICT_GCLB dicNew=new DICT_GCLB();
dicNew.GCLBText="-请选择-";
dicNew.GCLBId=0;
lsGCLB.Add(dicNew); return Content(WebHelper.Json(lsGCLB));
} public ActionResult GetAllArea()
{
List<DICT_Area> lsArea = basebll.GetAll<DICT_Area>();
DICT_Area dicNew=new DICT_Area();
dicNew.AreaText="-请选择-";
dicNew.AreaId=0;
lsArea.Add(dicNew);
return Content(WebHelper.Json(lsArea));
}
}

个人原创。欢迎转载,尊重劳动成果,引用注明来源。

http://blog.csdn.net/laokaizzz/article/details/25730813



版权声明:本文博客原创文章,博客,未经同意,不得转载。

entity framework 6 我写了一个公用数据类的更多相关文章

  1. Entity Framework 实体框架的形成之旅--基类接口的统一和异步操作的实现(3)

    在本系列的第一篇随笔<Entity Framework 实体框架的形成之旅--基于泛型的仓储模式的实体框架(1)>中介绍了Entity Framework 实体框架的一些基础知识,以及构建 ...

  2. 我写的一个ExcelHelper通用类,可用于读取或生成数据

    读取或生成EXCEL数据的方法有很多,一般常见的有: 1.通过OFFICE EXCEL组件,优点:读取与生成EXCEL文件方便,缺点:服务器上必须安装OFFICE软件,且进程无法及时释放 2.通过第三 ...

  3. 我写了一个java实体类,implements了Serializable接口,然后我如何让serialversionUID自动生成

    写了一个java实体类,implements了Serializable接口,让serialversionUID自动生成方法: 1.点击类旁边的警告符号: 2.选择Add generated seria ...

  4. 如何创建一个要素数据类 IField,IFieldEdit,IFields,IFieldsEditI,GeometryDef,IGeometryDefEdit接口

    如何创建一个要素数据类 创建要素类用到了IFeatureWorkspace.CreateFeatureClass方法,在这个方法中有众多的参数,为了满足这些参数,我们要学习和了解下面的接口. IFie ...

  5. 使用Entity Framework Core需要注意的一个全表查询问题

    .NET Core 迁移工作如火如荼,今天在使用 Entity Frameowork Core(又名EF Core)时写了下面这样的 LINQ 查询表达式: .Where(u => u.Id = ...

  6. Entity FrameWork对有外键关联的数据表的添加操作

    前天做了一个MVC Entity FrameWork项目,遇到有外键关联的数据编辑问题.当你编辑的时候,按照正常的逻辑,把每个字段的数据都对号入座了,然后点击保存按钮,本以为会顺理成章的编辑数据,但是 ...

  7. Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 更新关系数据

    Updating related data¶ 7 of 7 people found this helpful The Contoso University sample web applicatio ...

  8. Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 读取关系数据

    Reading related data¶ 9 of 9 people found this helpful The Contoso University sample web application ...

  9. Entity Framework(三):使用特性(数据注解)创建表结构

    一.理解Code First及其约定和配置 传统设计应用的方式都是由下而上的,即我们习惯优先考虑数据库,然后使用这个以数据为中心的方法在数据之上构建应用程序.这种方法非常适合于数据密集的应用或者数据库 ...

随机推荐

  1. 打印NSLog分类 Foundation+Log.m

    #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @implementation UIView(Log) + ...

  2. light oj 1047-neighbor house

    ime Limit:500MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu Description The people ...

  3. ubuntu安装greenplum依赖包

    ubuntu安装greenplum的过程中有两个比较难找的包,特地写出来给大家分享一下: 错误提示1:configure: error: header file <ldap.h> is r ...

  4. atlas z 轴

    问题源自一个帖子,因为上传的图比较多,就另开了这个贴写下自己的试验结果,原帖在下面链接中 http://game.ceeger.com/forum/read.php?tid=8911#info NGU ...

  5. 错误解决--oracle中出现ORA-01791: 不是 SELECTed 表达式 错误

    Oracle数据库,执行下面语句出现错误“ORA-01791: 不是 SELECTed 表达式”: select distinct t.name from auth_employee t order ...

  6. Mojo 自动发布接口

    get '/api/auto_publish/publish' => sub{ my $c = shift; my $env = $c->param('env'); my $app = $ ...

  7. HDU 4679 String

    String Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others) Total Sub ...

  8. 汉高澳大利亚sinox为什么不能下载源代码,因为sinox执行unix/linux/windows规划

    中国用户下载真正的澳大利亚sinox说完后sinox没有下载源代码. 这意味着,类似linux如下载linux 开源安装. 要知道.sinox并非linux. 首先,sinox是商业操作系统,就像 w ...

  9. android Listview,gridview局部刷新,部分刷新

    众所周知Listview和Gridview的刷新界面的方式是调用adapter.notifyDataSetChanged()进行界面刷新. 但是此方法有其弊端,他是将界面中的数据全部刷新一遍,不论数据 ...

  10. C#动态增加边框

    if (this.Width >= 600) { timer1.Enabled = false; } else { this.Width += 30; }