public class BaseDBService<T> where T : BaseModel
{
private readonly EFCoreFirst Context;
private IDbSet<T> _entities;
public BaseDBService()
{
Context = new EFCoreFirst();
}
public void Delete(long Id)
{
try
{
var data = Get(Id).FirstOrDefault();
if (data != null)
{
Entities.Remove(data);
Context.SaveChanges();
}
}
catch
{
}
}
public IQueryable<T> Get(long id)
{
try
{
var sql = Entities.Where(x=>x.Id==id);
return sql;
}
catch
{
return null;
}
}
public IQueryable<T> Query()
{
try
{
var sql = Entities.AsQueryable();
return sql;
}
catch
{
return null;
}
}
/// <summary>
/// 翻页查询
/// </summary>
/// <typeparam name="Tkey"></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> LoadPageItems<Tkey>(int pageSize, int pageIndex, out int total, Expression<Func<T, bool>> whereLambda, Func<T, Tkey> orderbyLambda, bool isAsc)
{
total = Entities.Where(whereLambda).Count();
if (isAsc)
{
var temp = Entities.Where(whereLambda).OrderBy<T, Tkey>(orderbyLambda)
.Skip(pageSize * (pageIndex - 1))
.Take(pageSize);
return temp.AsQueryable();
}
else
{
var temp = Entities.Where(whereLambda).OrderByDescending<T, Tkey>(orderbyLambda)
.Skip(pageSize * (pageIndex - 1))
.Take(pageSize);
return temp.AsQueryable();
}
}
public IQueryable<T> Query(Expression<Func<T, bool>> where)
{
return Query().Where(where);
}
public T Save(T Model)
{
if (Model.Id <= 0)
{
Add(Model);
return Model;
}
else
{
Update(Model);
return Model;
}
}
private void Update(T model)
{
Entities.Attach(model);
((IObjectContextAdapter)this.Context).ObjectContext.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
Context.SaveChanges();
}
private void Add(T model)
{
model.GUID = Guid.NewGuid().ToString();
model.IsDelet =false;
model.DateCreated = DateTime.Now;
Entities.Add(model);
Context.SaveChanges();
}
/// <summary>
/// 设置当前实体类的上下文实体
/// </summary>
protected virtual IDbSet<T> Entities
{
get
{
if (_entities == null)
{
_entities = Context.Set<T>();
}
return _entities;
}
}
}