using KPIServices.EF;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Web;
namespace KPIServices.DAL
{
public class BaseDAL where T : class
{
protected DbContext baseContext;
protected IDbSet objectSet;
public BaseDAL()
{
this.baseContext = new xnyykpidbEntities();
this.objectSet = baseContext.Set<T>();
}
public T GetByGuid(string guid)
{
return objectSet.Find(guid);
}
public T GetById(int id)
{
return objectSet.Find(id);
}
public IList<T> GetAll()
{
return objectSet.ToList<T>();
}
public IList<T> GetAll(System.Linq.Expressions.Expression<Func<T, bool>> whereCondition)
{
return objectSet.Where(whereCondition).ToList<T>();
}
public IList<T> GetAll<Tkey>(System.Linq.Expressions.Expression<Func<T, bool>> whereCondition, Func<T, Tkey> orderbyCondition, bool desc = false)
{
if (null == whereCondition)
{
if (desc)
{
return objectSet.OrderByDescending(orderbyCondition).ToList<T>();
}
else
{
return objectSet.OrderBy(orderbyCondition).ToList<T>();
}
}
else
{
if (desc)
{
return objectSet.Where(whereCondition).OrderByDescending(orderbyCondition).ToList<T>();
}
else
{
return objectSet.Where(whereCondition).OrderBy(orderbyCondition).ToList<T>();
}
}
}
/// <summary>
/// 分页查询 + 条件查询 + 排序
/// </summary>
/// <typeparam name="Tkey">泛型</typeparam>
/// <param name="pageSize">每页大小</param>
/// <param name="pageIndex">当前页码</param>
/// <param name="total">总数量</param>
/// <param name="whereLambda">查询条件</param>
/// <param name="orderbyLambda">排序条件</param>
/// <param name="isAsc">是否升序</param>
/// <returns>IQueryable 泛型集合</returns>
public IList<T> LoadPageItems<Tkey>(int pageSize, int pageIndex, out int total, System.Linq.Expressions.Expression<Func<T, bool>> whereCondition, Func<T, Tkey> orderbyLambda, bool isAsc)
{
total = objectSet.Where(whereCondition).Count();
if (isAsc)
{
var temp = objectSet.Where(whereCondition)
.OrderBy(orderbyLambda)
.Skip(pageSize * (pageIndex - 1))
.Take(pageSize).ToList<T>();
return temp;
}
else
{
var temp = objectSet.Where(whereCondition)
.OrderByDescending(orderbyLambda)
.Skip(pageSize * (pageIndex - 1))
.Take(pageSize).ToList<T>();
return temp;
}
}
public bool Delete(T entity)
{
objectSet.Remove(entity);
return SaveChanges();
return true;
}
public bool DeleteList(List<T> entity)
{
foreach (var ent in entity)
{
objectSet.Remove(ent);
}
return SaveChanges();
return true;
}
public bool Add(T entity)
{
objectSet.Add(entity);
return SaveChanges();
//return true;
}
public bool AddList(List<T> entity)
{
foreach (var ent in entity)
{
objectSet.Add(ent);
}
return SaveChanges();
//return true;
}
public bool Update(T entity)
{
//objectSet.(entity);
return SaveChanges();
return true;
}
bool SaveChanges()
{
try
{
baseContext.SaveChanges();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return false;
}
return true;
}
}
}
Z.EntityFramework.Extensions
用于大批量保存提高效率
下载地址
提取码:92mn