Entity Framework 增删改查基本操作(封装基类)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chwenbin/article/details/79111376

 分享一下自己在使用EF时,对增删改查基本操作的封装代码,一般在Biz层使用一个基类(因公司风格叫Biz层,其实就是DAL层)。

1.基类代码:使用虚方法子类可以重写。

public class BizBase<T> where T : class, new()
{
    //上下文对象
    protected WESMSEF dbContext = DbContextHelper.CreateDbContext<WESMSEF>();

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    public virtual int Add(T t)
    {
        dbContext.Entry<T>(t).State = EntityState.Added;
        return dbContext.SaveChanges();
    }

    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    public virtual int Update(T t)
    {
        dbContext.Entry<T>(t).State = EntityState.Modified;
        return dbContext.SaveChanges();
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    public virtual int Delete(T t)
    {
        dbContext.Entry<T>(t).State = EntityState.Deleted;
        return dbContext.SaveChanges();
    }
    
    /// <summary>
    /// 查询
    /// </summary>
    /// <param name="whereFun"></param>
    /// <param name="selectFun"></param>
    /// <returns></returns>
    public virtual IQueryable<T> Query(Expression<Func<T, bool>> whereFun = null, Expression<Func<T, T>> selectFun = null)
    {
        IQueryable<T> result = dbContext.Set<T>();
        if (whereFun != null) result = result.Where(whereFun);
        if (selectFun != null) result = result.Select(selectFun);
        return result;
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="pageNo">页码</param>
    /// <param name="pageCount">页数</param>
    /// <param name="whereFun">查询条件</param>
    /// <param name="selectFun">返回数据</param>
    /// <param name="orderByFun">排序</param>
    /// <param name="total">总数</param>
    /// <param name="isAsc">排序,默认升序</param>
    /// <returns>list</returns>
    public virtual List<T> PageQuery<S>(int pageNo, int pageCount, Expression<Func<T, bool>> whereFun,
        Expression<Func<T, T>> selectFun, Expression<Func<T, S>> orderByFun, out int total, bool isAsc = true)
    {
        total = 0;
         int startIndex = pageCount * (pageNo - 1);
        var list = dbContext.Set<T>().Where(whereFun);
        total = list.Count();
        if (total <= 0) return new List<T>();
        if (isAsc)
            list = list.OrderBy(orderByFun).Skip(startIndex).Take(pageCount).Select(selectFun);
        else
            list = list.OrderByDescending(orderByFun).Skip(startIndex).Take(pageCount).Select(selectFun);

        return list.ToList();
    }
}

2.子类代码通过继承子类已经有了增删改查基本操作,也可以扩展子类特有的操作。

/// <summary>
/// 用户子类
/// </summary>
public class BizUser : BizBase<User>
{
   
}



展开阅读全文

没有更多推荐了,返回首页