BaseRepository.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using Microsoft.EntityFrameworkCore;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel.DataAnnotations;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace ERP.Framework.WebApi
  10. {
  11. public class BaseRepository<T, TDbContext> where T : BaseEntity where TDbContext : DbContext
  12. {
  13. private TDbContext _context;
  14. public BaseRepository(TDbContext context)
  15. {
  16. _context = context;
  17. }
  18. public T? FirstOrDefault(Expression<Func<T, bool>> exp = null)
  19. {
  20. return Filter(exp).FirstOrDefault();
  21. }
  22. public void Add(T entity)
  23. {
  24. _context.Set<T>().Add(entity);
  25. Save();
  26. _context.Entry(entity).State = EntityState.Detached;
  27. }
  28. public void Save()
  29. {
  30. try
  31. {
  32. var entities = _context.ChangeTracker.Entries()
  33. .Where(e => e.State == EntityState.Added
  34. || e.State == EntityState.Modified)
  35. .Select(e => e.Entity);
  36. foreach (var entity in entities)
  37. {
  38. var validationContext = new ValidationContext(entity);
  39. Validator.ValidateObject(entity, validationContext, validateAllProperties: true);
  40. }
  41. _context.SaveChanges();
  42. }
  43. catch (ValidationException exc)
  44. {
  45. // Todo 抛出异常
  46. //Console.WriteLine($"{nameof(Save)} validation exception: {exc?.Message}");
  47. //throw (exc.InnerException as Exception ?? exc);
  48. }
  49. catch (Exception ex) //DbUpdateException
  50. {
  51. // Todo 抛出异常
  52. //throw (ex.InnerException as Exception ?? ex);
  53. }
  54. }
  55. private IQueryable<T> Filter(Expression<Func<T, bool>> exp)
  56. {
  57. var dbSet = _context.Set<T>().AsNoTracking().AsQueryable();
  58. if (exp != null)
  59. dbSet = dbSet.Where(exp);
  60. return dbSet;
  61. }
  62. }
  63. }