using Microsoft.EntityFrameworkCore; using NPOI.SS.Formula.Functions; using ProductionLineMonitor.Core.IRepositories; using ProductionLineMonitor.Core.Models; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ProductionLineMonitor.EntityFramework.Repositories { public class BaseRepository : IBaseRepository where T : Base { protected readonly ProductionLineContext _context; protected readonly DbSet _entities; public BaseRepository(ProductionLineContext context) { _context = context; _entities = context.Set(); } public bool Any(Expression>? filter = null) { return _entities.Any(filter); } public void Create(T t) { _entities.Add(t); } public void Create(IEnumerable ts) { _entities.AddRange(ts); } public void Delete(T t) { _entities.Remove(t); } public void Delete(string id) { var t = _entities.Find(id); if (t != null) { _entities.Remove(t); } } public void Delete(IEnumerable ts) { _entities.RemoveRange(ts); } public T FirstOrDefault(Expression>? filter = null) { if (filter == null) { return _entities.AsNoTracking().FirstOrDefault(); } return _entities.AsNoTracking().FirstOrDefault(filter); } public T GetById(string id) { return _entities.Find(id); } public IQueryable GetLastList(int lastNumber = 10) { return _entities.OrderByDescending(x => x.CreateTime).TakeLast(lastNumber); } public IQueryable GetList(Expression>? filter = null) { if (filter == null) { return _entities; } return _entities.Where(filter); } public IQueryable GetListAsync( Expression>? filter = null) { if (filter == null) { return _entities; } return _entities.Where(filter); } public IQueryable GetPageList( out int total, int pageNo = 1, int pageSize = 10, Func, IOrderedQueryable>? orderBy = null, Expression>? filter = null) { IQueryable query = _entities; if (orderBy != null) { query = orderBy(query); } if (filter != null) { query = query.Where(filter); } //total = query.Count() / pageSize; //total = total == 0 ? 1 : total; total = query.Count(); return query.Skip(pageSize * (pageNo - 1)).Take(pageSize); } public void Update(T t) { _entities.Update(t); } public void Update(IEnumerable ts) { _entities.UpdateRange(ts); } } }