水平有限,如有错误,还望指正。
一部分代码。重在思想。
1.唯一数据会话层
// 创建数据会话层工厂
public class DbSessionFactory//<T> where T : class,new()
{
/// <summary>
/// 跟创建唯一数据上下文一样。保证线程内数据会话层唯一。
/// </summary>
/// <returns></returns>
public static IDbSession GetDbSession()
{
IDbSession DBSession = (IDbSession)CallContext.GetData("DBSession");
if (DBSession == null)
{
DBSession = new DbSession();
CallContext.SetData("DBSession", DBSession);
}
return DBSession;
}
}
2.实体BLL层
public class UsersBLL : BaseBLL<Users>, IUserBLL
{
// 独有方法。
/// <summary>
/// 实现了父类的方法。
/// </summary>
public override void SetCurrentDAL()
{
this.CurrentDAL = dbsession.CurrentDAL("Users") as UsersDAL;//new UsersDAL();
}
/// <summary>
/// 根据邮箱或用户名查询用户。
/// </summary>
/// <param name="search"></param>
/// <returns></returns>
public IQueryable<Users> SearchByUserInfo(SearchUserInfo search)
{
int pageIndex = search.PageIndex;
int pageSize = search.PageSize;
var res = this.CurrentDAL.GetEntities(c => true);
if (!string.IsNullOrEmpty(search.Name))
{
res = CurrentDAL.GetEntities(c => c.Name.Contains(search.Name));
}
if (!string.IsNullOrEmpty(search.Email))
{
res = CurrentDAL.GetEntities(c => c.Mail.Contains(search.Email));
}
search.TotalCount = res.Count<Users>();
return res.OrderBy<Users, int>(c => c.Id).Skip<Users>((pageIndex - 1) * pageSize).Take<Users>(pageSize);
}
}
3.实体抽象基类
public abstract class BaseBLL<T> where T : class,new()
{
public IDBSession.IDbSession dbsession
{
get { return DBSession.DbSessionFactory.GetDbSession(); }
}
// 从子类中获取对应的IEntityDAL
public IBaseDAL<T> CurrentDAL;
public abstract void SetCurrentDAL();
public BaseBLL()
{
SetCurrentDAL();
}
public IQueryable<T> GetEntities(Func<T, bool> WhereLambda)
{
//return CurrentDAL.GetEntities(WhereLambda);
var entities = CurrentDAL.GetEntities(WhereLambda);
if (dbsession.SaveChanges() > 0)
{
return entities;
}
else
{ return null; }
}
public IQueryable<T> GetEntitiesByPaging<type>(int pageIndex, int pageSize, out int recordCount, bool isASC, Func<T, type> orderByLambda, Func<T, bool> whereLamba)
{
return CurrentDAL.GetEntitiesByPaging<type>(pageIndex, pageSize, out recordCount, isASC, orderByLambda, whereLamba);
}
public T Add(T entity)
{
//return CurrentDAL.Add(entity);
var e = CurrentDAL.Add(entity);
if (dbsession.SaveChanges() > 0)
{
return e;
}
else
{ return null; }
}
public bool Edit(T entity)
{
//return CurrentDAL.Edit(entity);
var e = CurrentDAL.Edit(entity);
if (dbsession.SaveChanges() > 0)
{
return true;
}
else
{ return false; }
}
public bool Delete(T entity)
{
//return CurrentDAL.Delete(entity);
var e = CurrentDAL.Delete(entity);
if (dbsession.SaveChanges() > 0)
{
return true;
}
else
{ return false; }
}
}
------------------------------over------------------------------