BaseRepository.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using Microsoft.EntityFrameworkCore;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Linq.Expressions;
  4. namespace ERP.Framework.WebApi
  5. {
  6. public class BaseRepository<T, TDbContext> where T : BaseEntity where TDbContext : DbContext
  7. {
  8. public TDbContext Context;
  9. public BaseRepository(TDbContext context)
  10. {
  11. Context = context;
  12. }
  13. public T? FirstOrDefault(Expression<Func<T, bool>>? exp = null)
  14. {
  15. return Filter(exp).FirstOrDefault();
  16. }
  17. public Task<T?> FirstOrDefaultAsync(Expression<Func<T, bool>>? exp = null)
  18. {
  19. return Filter(exp).FirstOrDefaultAsync();
  20. }
  21. public List<T> List(Expression<Func<T, bool>>? exp = null)
  22. {
  23. return Filter(exp).ToList();
  24. }
  25. public void Add(T entity)
  26. {
  27. Context.Set<T>().Add(entity);
  28. Save();
  29. // EF不再跟踪实体更改
  30. Context.Entry(entity).State = EntityState.Detached;
  31. }
  32. public async Task<bool> AddAsync(T entity)
  33. {
  34. await Context.Set<T>().AddAsync(entity);
  35. return await TaskSave();
  36. }
  37. public void Save()
  38. {
  39. try
  40. {
  41. var entities = Context.ChangeTracker.Entries()
  42. .Where(e => e.State == EntityState.Added
  43. || e.State == EntityState.Modified)
  44. .Select(e => e.Entity);
  45. foreach (var entity in entities)
  46. {
  47. var validationContext = new ValidationContext(entity);
  48. Validator.ValidateObject(entity, validationContext, validateAllProperties: true);
  49. }
  50. Context.SaveChanges();
  51. }
  52. catch (ValidationException exc)
  53. {
  54. // Todo 抛出异常
  55. //Console.WriteLine($"{nameof(Save)} validation exception: {exc?.Message}");
  56. //throw (exc.InnerException as Exception ?? exc);
  57. }
  58. catch (Exception ex) //DbUpdateException
  59. {
  60. // Todo 抛出异常
  61. //throw (ex.InnerException as Exception ?? ex);
  62. }
  63. }
  64. public Task<bool> TaskSave()
  65. {
  66. try
  67. {
  68. var entities = Context.ChangeTracker.Entries()
  69. .Where(e => e.State == EntityState.Added
  70. || e.State == EntityState.Modified)
  71. .Select(e => e.Entity);
  72. foreach (var entity in entities)
  73. {
  74. var validationContext = new ValidationContext(entity);
  75. Validator.ValidateObject(entity, validationContext, validateAllProperties: true);
  76. }
  77. var result = Context.SaveChanges();
  78. return Task.FromResult(result > 0);
  79. }
  80. catch (Exception ex)
  81. {
  82. // Todo 打印日志
  83. return Task.FromResult(false); ;
  84. }
  85. }
  86. private IQueryable<T> Filter(Expression<Func<T, bool>>? exp)
  87. {
  88. var dbSet = Context.Set<T>().AsNoTracking().AsQueryable();
  89. if (exp != null)
  90. dbSet = dbSet.Where(exp);
  91. return dbSet;
  92. }
  93. }
  94. }