entity framework 公共类

public abstract class BaseService<T> where T : class
{
    private static readonly DatabaseContext db = new DatabaseContext();

    public static T Add(T entity)
    {
        db.Entry<T>(entity).State = EntityState.Added;
        db.SaveChanges();
        return entity;
    }

    public static int Count(Expression<Func<T, bool>> predicate)
    {
        return db.Set<T>().Count(predicate);
    }

    public static bool Update(T entity)
    {
        db.Set<T>().Attach(entity);
        db.Entry<T>(entity).State = EntityState.Modified;
        return db.SaveChanges() > 0;
    }

    public static bool Delete(T entiry)
    {
        db.Set<T>().Attach(entiry);
        db.Entry<T>(entiry).State = EntityState.Deleted;
        return db.SaveChanges() > 0;
    }

    public static bool Exist(Expression<Func<T, bool>> predicate)
    {
        return db.Set<T>().Any(predicate);
    }

    public static T Find(Expression<Func<T, bool>> predicate)
    {
        return db.Set<T>().FirstOrDefault(predicate);
    }

    public static IQueryable<T> FindList(Expression<Func<T, bool>> predicate, int pageIndex, int pageSize, int total, params OrderFieldModel[] orderByExpression)
    {
        var query = db.Set<T>().Where(predicate);

        var parameter = Expression.Parameter(typeof(T), "o");
        if (orderByExpression != null && orderByExpression.Length > 0)
        {
            foreach (var orderField in orderByExpression)
            {
                var property = typeof(T).GetProperty(orderField.PropertyName);
                var propertyAccess = Expression.MakeMemberAccess(parameter, property);
                var orderByExp = Expression.Lambda(propertyAccess, parameter);
                string orderName = orderField.IsDESC ? "OrderByDescending" : "OrderBy";
                MethodCallExpression resultExp = Expression.Call(typeof(Queryable), orderName, new Type[] { typeof(T), property.PropertyType }, query.Expression, Expression.Quote(orderByExp));
                query = query.Provider.CreateQuery<T>(resultExp);
            }
        }
        return db.Set<T>().Where(predicate);
    }
}

 

你可能感兴趣的:(entity framework 公共类)