You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuEfDataAccess.cs 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq.Expressions;
  5. using Luticate2.Utils.Dbo.Result;
  6. using Microsoft.EntityFrameworkCore;
  7. using Microsoft.Extensions.DependencyInjection;
  8. namespace Luticate2.Utils.DataAccess
  9. {
  10. public abstract class LuEfDataAccess<TModel, TDbContext> : LuDataAccess
  11. where TModel : class
  12. where TDbContext : DbContext
  13. {
  14. private readonly IServiceProvider _serviceProvider;
  15. protected LuEfTransactionScope TransactionScope => _serviceProvider.GetService<LuEfTransactionScope>();
  16. protected LuEfDataAccess(IServiceProvider serviceProvider)
  17. {
  18. _serviceProvider = serviceProvider;
  19. }
  20. protected abstract DbSet<TModel> GetTable(TDbContext db);
  21. protected virtual LuResult<T> HandleError<T>(Exception e)
  22. {
  23. return null;
  24. }
  25. public virtual LuResult<T> Execute<T>(Func<TDbContext, DbSet<TModel>, LuResult<T>> func)
  26. {
  27. try
  28. {
  29. var transactedDb = TransactionScope.GetTransactedDbContext<TDbContext>();
  30. if (transactedDb == null)
  31. {
  32. using (var db = _serviceProvider.GetService<TDbContext>())
  33. {
  34. return func(db, GetTable(db));
  35. }
  36. }
  37. return func(transactedDb, GetTable(transactedDb));
  38. }
  39. catch (Exception e)
  40. {
  41. var err = HandleError<T>(e);
  42. if (null != err)
  43. {
  44. return err;
  45. }
  46. return LuResult<T>.Error(LuStatus.DbError, e);
  47. }
  48. }
  49. public static Expression<Func<TModel, bool>> GetExpression(params KeyValuePair<string, object>[] keys)
  50. {
  51. var param = Expression.Parameter(typeof(TModel), "x");
  52. Expression totalExp = null;
  53. foreach (var pair in keys)
  54. {
  55. var equalExp = Expression.Equal(Expression.Property(param, pair.Key), Expression.Constant(pair.Value));
  56. totalExp = totalExp == null ? equalExp : Expression.And(equalExp, totalExp);
  57. }
  58. return Expression.Lambda<Func<TModel, bool>>(totalExp, param);
  59. }
  60. public bool BeginTransaction(TDbContext context, IsolationLevel? level = null)
  61. {
  62. return TransactionScope.BeginTransaction(context, level);
  63. }
  64. public void CommitTransaction(bool transact)
  65. {
  66. if (transact)
  67. {
  68. TransactionScope.CommitTransaction<TDbContext>();
  69. }
  70. }
  71. public void RollbackTransaction(bool transact)
  72. {
  73. if (transact)
  74. {
  75. TransactionScope.RollbackTransaction<TDbContext>();
  76. }
  77. }
  78. }
  79. }