DbExtention.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using Microsoft.Data.SqlClient;
  2. using Microsoft.EntityFrameworkCore;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace EVCB_OCPP.WSServer.Helper
  10. {
  11. public static class DbExtention
  12. {
  13. public static async Task<(bool, int)> SaveChangesUntilSuccessAsync(this DbContext context)
  14. {
  15. bool result = false;
  16. int rows = 0;
  17. do
  18. {
  19. (result, rows) = await context.TrySaveChangesAsync();
  20. }
  21. while (!result);
  22. return (result, rows);
  23. }
  24. public static async Task<(bool, int)> TrySaveChangesAsync(this DbContext context)
  25. {
  26. int affectedRows = 0;
  27. try
  28. {
  29. affectedRows = await context.SaveChangesAsync();
  30. return (true, affectedRows);
  31. }
  32. catch (Exception e)
  33. {
  34. return (false, affectedRows);
  35. }
  36. }
  37. public static void AddInsertMeterValueRecordSqlParameters(this List<SqlParameter> sqlParameters,
  38. string chargeBoxId, byte connectorId, decimal value, DateTime createdOn
  39. ,int contextId, int formatId, int measurandId, int phaseId
  40. ,int locationId,int unitId,int transactionId)
  41. {
  42. List<SqlParameter> parameter = new List<SqlParameter>
  43. {
  44. new SqlParameter("ChargeBoxId", SqlDbType.NVarChar, 50){ Value = chargeBoxId },
  45. new SqlParameter("ConnectorId", SqlDbType.TinyInt) { Value = connectorId },
  46. new SqlParameter("Value", SqlDbType.Decimal) { Value = value, Precision = 18, Scale = 8 },
  47. new SqlParameter("CreatedOn", SqlDbType.DateTime) { Value = createdOn },
  48. new SqlParameter("ContextId", SqlDbType.Int) { Value = contextId },
  49. new SqlParameter("FormatId", SqlDbType.Int) { Value = formatId },
  50. new SqlParameter("MeasurandId", SqlDbType.Int) { Value = measurandId },
  51. new SqlParameter("PhaseId", SqlDbType.Int) { Value = phaseId },
  52. new SqlParameter("LocationId", SqlDbType.Int) { Value = locationId },
  53. new SqlParameter("UnitId", SqlDbType.Int) { Value = unitId },
  54. new SqlParameter("TransactionId", SqlDbType.Int) { Value = transactionId },
  55. };
  56. sqlParameters.AddRange(parameter);
  57. }
  58. }
  59. }