entity framework 公共类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 公共类的主要内容,如果未能解决你的问题,请参考以下文章

Entity Framework 5.0系列之自动生成Code First代码

.Net Entity Framework连接MySql

.NET Entity Framework(EF)使用SqlQuery直接操作SQL查询语句或者执行过程

Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作

Entity Framework 6 不适用于时态表

带有 ADO.NET Entity Framework 的内部类