BaseRepository.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 void Add(T entity)
  22. {
  23. Context.Set<T>().Add(entity);
  24. Save();
  25. // EF不再跟踪实体更改
  26. Context.Entry(entity).State = EntityState.Detached;
  27. }
  28. public async Task<bool> AddAsync(T entity)
  29. {
  30. await Context.Set<T>().AddAsync(entity);
  31. return await TaskSave();
  32. }
  33. public void Save()
  34. {
  35. try
  36. {
  37. var entities = Context.ChangeTracker.Entries()
  38. .Where(e => e.State == EntityState.Added
  39. || e.State == EntityState.Modified)
  40. .Select(e => e.Entity);
  41. foreach (var entity in entities)
  42. {
  43. var validationContext = new ValidationContext(entity);
  44. Validator.ValidateObject(entity, validationContext, validateAllProperties: true);
  45. }
  46. Context.SaveChanges();
  47. }
  48. catch (ValidationException exc)
  49. {
  50. // Todo 抛出异常
  51. //Console.WriteLine($"{nameof(Save)} validation exception: {exc?.Message}");
  52. //throw (exc.InnerException as Exception ?? exc);
  53. }
  54. catch (Exception ex) //DbUpdateException
  55. {
  56. // Todo 抛出异常
  57. //throw (ex.InnerException as Exception ?? ex);
  58. }
  59. }
  60. public Task<bool> TaskSave()
  61. {
  62. try
  63. {
  64. var entities = Context.ChangeTracker.Entries()
  65. .Where(e => e.State == EntityState.Added
  66. || e.State == EntityState.Modified)
  67. .Select(e => e.Entity);
  68. foreach (var entity in entities)
  69. {
  70. var validationContext = new ValidationContext(entity);
  71. Validator.ValidateObject(entity, validationContext, validateAllProperties: true);
  72. }
  73. var result = Context.SaveChanges();
  74. return Task.FromResult(result > 0);
  75. }
  76. catch (Exception ex)
  77. {
  78. // Todo 打印日志
  79. return Task.FromResult(false); ;
  80. }
  81. }
  82. private IQueryable<T> Filter(Expression<Func<T, bool>>? exp)
  83. {
  84. var dbSet = Context.Set<T>().AsNoTracking().AsQueryable();
  85. if (exp != null)
  86. dbSet = dbSet.Where(exp);
  87. return dbSet;
  88. }
  89. }
  90. }