在EF的code frist下写稳健的权限管理系统:仓储设计(三)

时间:2022-05-09 15:17:50
public class BaseRepository<T>:IBaseRepository<T> where T : class
{
protected EfConnection DbContext = ContextFactory.GetCurrentContext(); public bool Insert(T entity)
{
DbContext.Set<T>().Add(entity);
return DbContext.SaveChanges()>;
} public bool InsertBatch(List<T> datas)
{
DbContext.Set<T>().AddRange(datas);
return DbContext.SaveChanges() > ;
} public void Update(T entity)
{
DbContext.Set<T>().Attach(entity);
DbContext.Entry<T>(entity).State = EntityState.Modified;
DbContext.SaveChanges();
} public void Delete(Expression<Func<T, bool>> expression)
{
var reDeleteds = DbContext.Set<T>().Where(expression);
if (!reDeleteds.Any()) return; foreach (var reDeleted in reDeleteds)
{
DbContext.Entry<T>(reDeleted).State = EntityState.Deleted;
} DbContext.SaveChanges();
} public IQueryable<T> GetAll()
{
return DbContext.Set<T>().AsQueryable();
} public T Find(Expression<Func<T, bool>> expression)
{
return DbContext.Set<T>().FirstOrDefault(expression);
}
}

BaseRepository

public interface IBaseRepository<T> where T : class
{
/// <summary>
/// 添加
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>添加后的数据实体</returns>
bool Insert(T entity); /// <summary>
/// 批量添加
/// </summary>
/// <param name="datas"></param>
/// <returns></returns>
bool InsertBatch(List<T> datas); /// <summary>
/// 更新
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>是否成功</returns>
void Update(T entity); /// <summary>
/// 删除
/// </summary>
/// <param name="expression">删除条件</param>
/// <returns>是否成功</returns>
void Delete(Expression<Func<T, bool>> expression); /// <summary>
/// 获取所有
/// </summary>
/// <returns></returns>
IQueryable<T> GetAll(); /// <summary>
/// 查找数据
/// </summary>
/// <param name="expression">查询条件</param>
/// <returns>实体</returns>
T Find(Expression<Func<T, bool>> expression);
}

IBaseRepository

基础仓储的接口和EF中的实现