OA项目线程内共享上下文实例(二)
DbSession的作用:
1.拥有所有Dal的实例。
2.SaveChange()把实体进行一次整体的提交
public class DbSession { public IUserInfoDal UserInfoDal { get { return StaticDalFactory.GetUserInfoDal(); } } public IOrderInfoDal OrderInfoDal { get { return StaticDalFactory.GetOrderInfoDal(); } } /// /// 拿到当前的EF的上下文,然后进行 把修改实体进行一个整体提交。 /// /// public int SaveChanges() { return DbContextFactory.GetCurrentDbContext().SaveChanges(); } }
IDbSession的代码:
public interface IDbSession { IUserInfoDal UserInfoDal { get; } IOrderInfoDal OrderInfoDal { get; } int SaveChanges(); }
DbContextFactory的GetCurrentDbContext方法:
public class DbContextFactory { public static DbContext GetCurrentDbContext() { //一次请求共用一个实例 DbContext db = CallContext.GetData("DbContext") as DbContext; if (db == null) { db = new DataModelContainer(); CallContext.SetData("DbContext", db); } return db; } }
DbSessionFactory的封装:
/// /// 一次请求共用一个DbSession实例 /// public class DbSessionFactory { public static IDbSession GetCurrentDbSession() { IDbSession db = CallContext.GetData("DbSession") as IDbSession; if (db == null) { db = new DbSession(); CallContext.SetData("DbSession", db); } return db; } }
在UserInfoService中通过工厂模式获取Session:
//通过工厂模式获取Session private IDbSession dbSession = DbSessionFactory.GetCurrentDbSession();
BaseService的方法:
/// /// 父类要逼迫自己给父类的一个属性赋值 赋值的操作必须在父类的方法调用之前执行 /// /// public abstract class BaseService where T:class ,new() { public IBaseDal CurrentDal { get; set; } /// /// DbSession 做成属性 /// public IDbSession DbSession { get { return DbSessionFactory.GetCurrentDbSession(); } } /// /// 基类的构造函数 /// public BaseService() { //调用了抽象方法 SetCurrentDal(); } //抽象方法:要求子类必须实现抽象方法,对此方法进行重写 public abstract void SetCurrentDal(); /// /// 用到的时候在去查询 IQueryable 转换成 Queryable 集合 取代上面的方法 /// /// /// public IQueryable GetEntites(Expression> whereLambda) { return CurrentDal.GetEntites(whereLambda); } /// /// 分页的语句 /// /// /// /// /// /// public IQueryable GetPageEntites(int pageSize, int pageIndex, out int total, Expression> whereLambda, Expression> orderByLambda, bool isAsc) { return CurrentDal.GetPageEntites(pageSize, pageIndex, out total, whereLambda, orderByLambda, isAsc); } /// /// 增加 /// /// /// public T Add(T entity) { CurrentDal.Add(entity); DbSession.SaveChanges(); return entity; } /// /// 修改 /// /// /// public bool Update(T entity) { CurrentDal.Update(entity); return DbSession.SaveChanges() > 0; } /// /// 删除 /// /// /// public bool Delete(T entity) { CurrentDal.Delete(entity); return DbSession.SaveChanges() > 0; } }
UserInfoService的方法:
public class UserInfoService:BaseService { public override void SetCurrentDal() { CurrentDal = this.DbSession.UserInfoDal; } }
OrderInfoService 的方法:
public class OrderInfoService:BaseService { /// /// 赋值给当前的Dal /// public override void SetCurrentDal() { CurrentDal = DbSession.OrderInfoDal; } }
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~