Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

LuEfDataAccess.cs 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. public virtual LuResult<T> Execute<T>(Func<TDbContext, DbSet<TModel>, LuResult<T>> func)
  22. {
  23. try
  24. {
  25. var transactedDb = TransactionScope.GetTransactedDbContext<TDbContext>();
  26. if (transactedDb == null)
  27. {
  28. using (var db = _serviceProvider.GetService<TDbContext>())
  29. {
  30. return func(db, GetTable(db));
  31. }
  32. }
  33. return func(transactedDb, GetTable(transactedDb));
  34. }
  35. catch (Exception e)
  36. {
  37. return LuResult<T>.Error(LuStatus.DbError, e);
  38. }
  39. }
  40. public static Expression<Func<TModel, bool>> GetExpression(params KeyValuePair<string, object>[] keys)
  41. {
  42. var param = Expression.Parameter(typeof(TModel), "x");
  43. Expression totalExp = null;
  44. foreach (var pair in keys)
  45. {
  46. var equalExp = Expression.Equal(Expression.Property(param, pair.Key), Expression.Constant(pair.Value));
  47. totalExp = totalExp == null ? equalExp : Expression.And(equalExp, totalExp);
  48. }
  49. return Expression.Lambda<Func<TModel, bool>>(totalExp, param);
  50. }
  51. public bool BeginTransaction(TDbContext context, IsolationLevel? level = null)
  52. {
  53. return TransactionScope.BeginTransaction(context, level);
  54. }
  55. public void CommitTransaction(bool transact)
  56. {
  57. if (transact)
  58. {
  59. TransactionScope.CommitTransaction<TDbContext>();
  60. }
  61. }
  62. public void RollbackTransaction(bool transact)
  63. {
  64. if (transact)
  65. {
  66. TransactionScope.RollbackTransaction<TDbContext>();
  67. }
  68. }
  69. }
  70. }