public class BaseService<T> where T:BaseEntity
{
protected Model DB { get; set; }
public BaseService(Model db) {
DB = db;
}
#region 添加
public long Add(T model) {
DB.Entry<T>(model).State = EntityState.Added;
DB.SaveChanges();
return model.Id;
}
public bool AddBool(T model)
{
DB.Entry<T>(model).State = EntityState.Added;
return DB.SaveChanges()>0;
}
#endregion
#region 删除
public bool Delete(T model) {
DB.Set<T>().Attach(model);
model.IsDeleted = true;
DB.Entry<T>(model).State = EntityState.Modified;
return DB.SaveChanges() > 0;
}
public bool Delete(long id)
{
var t = DB.Set<T>().Find(id);
if (t == null || t.IsDeleted)
{
return true;
}
t.IsDeleted = true;
return DB.SaveChanges() > 0;
}
#endregion
#region 修改
public bool Update(T model) {
DB.Set<T>().Attach(model);
DB.Entry<T>(model).State = EntityState.Modified;
return DB.SaveChanges() > 0;
}
#endregion
#region 查询单个数据
public T Get(Expression<Func<T, bool>> whereLambda) {
return DB.Set<T>().FirstOrDefault(whereLambda);
}
#endregion
#region 查询列表
public IQueryable<T> GetList(Expression<Func<T, bool>> whereLambda) {
return DB.Set<T>().Where(p => p.IsDeleted == false).Where(whereLambda);
}
public IQueryable<T> GetList<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> OrderLamda,bool isASC=true)
{
var list= GetList(whereLambda);
if (isASC == true)
{
return list.OrderBy(OrderLamda);
}
else {
return list.OrderByDescending(OrderLamda);
}
}
public IQueryable<T> GetPagedList<TKey>(int start, int pageSize, ref long rowCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderBy, bool isAsc = true)
{
var list = GetList(whereLambda, orderBy, isAsc);
rowCount = list.LongCount();
return list.Skip(start).Take(pageSize);
}
#endregion
}