123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- 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<T> : IBaseRepository<T> where T : Base
- {
- protected readonly ProductionLineContext _context;
- protected readonly DbSet<T> _entities;
- public BaseRepository(ProductionLineContext context)
- {
- _context = context;
- _entities = context.Set<T>();
- }
- public bool Any(Expression<Func<T, bool>>? filter = null)
- {
- return _entities.Any(filter);
- }
- public void Create(T t)
- {
- _entities.Add(t);
- }
- public void Create(IEnumerable<T> 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<T> ts)
- {
- _entities.RemoveRange(ts);
- }
- public T FirstOrDefault(Expression<Func<T, bool>>? 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<T> GetLastList(int lastNumber = 10)
- {
- return _entities.OrderByDescending(x => x.CreateTime).TakeLast(lastNumber);
- }
- public IQueryable<T> GetList(Expression<Func<T, bool>>? filter = null)
- {
- if (filter == null)
- {
- return _entities;
- }
- return _entities.Where(filter);
- }
- public IQueryable<T> GetListAsync(
- Expression<Func<T, bool>>? filter = null)
- {
- if (filter == null)
- {
- return _entities;
- }
- return _entities.Where(filter);
- }
- public IQueryable<T> GetPageList(
- out int total, int pageNo = 1, int pageSize = 10,
- Func<IQueryable<T>, IOrderedQueryable<T>>? orderBy = null, Expression<Func<T, bool>>? filter = null)
- {
- IQueryable<T> 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<T> ts)
- {
- _entities.UpdateRange(ts);
- }
- }
- }
|