EntityFramework Core 封装

public class EntityBaseRepository<T> : IEntityBaseRepository<T>

where T : class, IEntityBase, new()

{

private SchedulerContext _context;

#region Properties

public EntityBaseRepository(SchedulerContext context)

{

_context = context;

}

#endregion

public virtual IEnumerable<T> GetAll()

{

return _context.Set<T>().AsEnumerable();

}

public virtual int Count()

{

return _context.Set<T>().Count();

}

public virtual IEnumerable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)

{

IQueryable<T> query = _context.Set<T>();

foreach (var includeProperty in includeProperties)

{

query = query.Include(includeProperty);

}

return query.AsEnumerable();

}

public T GetSingle(int id)

{

return _context.Set<T>().FirstOrDefault(x => x.Id == id);

}

public T GetSingle(Expression<Func<T, bool>> predicate)

{

return _context.Set<T>().FirstOrDefault(predicate);

}

public T GetSingle(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)

{

IQueryable<T> query = _context.Set<T>();

foreach (var includeProperty in includeProperties)

{

query = query.Include(includeProperty);

}

return query.Where(predicate).FirstOrDefault();

}

public virtual IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate)

{

return _context.Set<T>().Where(predicate);

}

public virtual void Add(T entity)

{

EntityEntry dbEntityEntry = _context.Entry<T>(entity);

_context.Set<T>().Add(entity);

}

public virtual void Update(T entity)

{

EntityEntry dbEntityEntry = _context.Entry<T>(entity);

dbEntityEntry.State = EntityState.Modified;

}

public virtual void Delete(T entity)

{

EntityEntry dbEntityEntry = _context.Entry<T>(entity);

dbEntityEntry.State = EntityState.Deleted;

}

public virtual void DeleteWhere(Expression<Func<T, bool>> predicate)

{

IEnumerable<T> entities = _context.Set<T>().Where(predicate);

foreach(var entity in entities)

{

_context.Entry<T>(entity).State = EntityState.Deleted;

}

}

public virtual void Commit()

{

_context.SaveChanges();

}

}




本文转自94cool博客园博客,原文链接:http://www.cnblogs.com/94cool/p/5912088.html如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值