【Design】线程中共享上下文实例 简单工厂 切换上下文

在BaseDal中,一般都是直接使用具体上下文实例

DataModelContainer db = new DataModelContainer();

在项目中经常会更改需求,如果现在的DataModeContainer不适用了,要更改了

可以通过基类DbContext作为返回值,只需要更改return new DataModelContainer();就好了

public class DbContextFactory
{
    public static DbContext GetCurrentDbContext()
    {
        //return new DataModelContainer();
        DbContext db = CallContext.GetData("DbContext") as DbContext;
        if (db == null)
        {
            db = new DataModelContainer();
            CallContext.SetData("DbContext", db);
        }

        return db;
    }
}

在BaseDal中

public DbContext Db
{
    get { return DbContextFactory.GetCurrentDbContext(); }
}

 

public class BaseDal<T> where T : class, new()
{
    //DataModelContainer db = new DataModelContainer();

    public DbContext Db
    {
        get { return DbContextFactory.GetCurrentDbContext(); }
    }

    /// <summary>
    /// 添加
    /// </summary>
    public T Add(T entity)
    {
        Db.Set<T>().Add(entity);
        Db.SaveChanges();
        return entity;
    }

    /// <summary>
    /// 修改
    /// </summary>
    public bool Update(T entity)
    {
        Db.Entry(entity).State = EntityState.Modified;
        return Db.SaveChanges() > 0;
    }

    /// <summary>
    /// 删除
    /// </summary>
    public bool Delete(T entity)
    {
        Db.Entry(entity).State = EntityState.Deleted;
        return Db.SaveChanges() > 0;
    }

    /// <summary>
    /// 通过参数获取信息
    /// </summary>
    public IQueryable<T> GetEntities(Expression<Func<T, bool>> whereLambda)
    {
        return Db.Set<T>().Where(whereLambda).AsQueryable();
    }

    /// <summary>
    /// 分页
    /// </summary>
    /// <typeparam name="S">排序对象</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></returns>
    public IQueryable<T> GetPageEntities<S>(int pageSize, int pageIndex, out int total,
        Expression<Func<T, bool>> whereLambda,
        Expression<Func<T, S>> orderByLambda,
        bool isAsc)
    {
        total = Db.Set<T>().Where(whereLambda).Count();

        if (isAsc)
        {
            var temp = Db.Set<T>().Where(whereLambda)
                .OrderBy(orderByLambda)
                .Skip(pageSize * (pageIndex - 1))
                .Take(pageSize).AsQueryable();
            return temp;
        }
        else
        {
            var temp = Db.Set<T>().Where(whereLambda)
            .OrderByDescending(orderByLambda)
            .Skip(pageSize * (pageIndex - 1))
            .Take(pageSize).AsQueryable();
            return temp;
        }

    }
}

 

相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页