Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

SqlServerBasicManager.cs 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity;
  4. using System.Linq.Expressions;
  5. using iiie.Logs.DataAccess;
  6. using iiie.Logs.DBO;
  7. namespace iiie.WebApiUtils.BusinessManager
  8. {
  9. /// <summary>
  10. /// Helper for SQL Server data access
  11. /// </summary>
  12. public abstract class SqlServerBasicManager<TDbObject, TEntities, TThis>
  13. where TDbObject : class
  14. where TEntities : DbContext, new()
  15. where TThis : SqlServerBasicManager<TDbObject, TEntities, TThis>, new()
  16. {
  17. /// <summary>
  18. /// Return the table to be used
  19. /// </summary>
  20. /// <param name="db">The database</param>
  21. /// <returns>The table instance</returns>
  22. public abstract DbSet<TDbObject> GetTable(TEntities db);
  23. /// <summary>
  24. /// Return the database table to use
  25. /// </summary>
  26. /// <param name="db">The database instance</param>
  27. /// <returns>The table</returns>
  28. public static DbSet<TDbObject> GetTableStatic(TEntities db)
  29. {
  30. var type = new TThis();
  31. return type.GetTable(db);
  32. }
  33. /// <summary>
  34. /// Get a predicate form the given keys and values
  35. /// </summary>
  36. /// <param name="keys">The keys and values to select data</param>
  37. /// <returns>The predicate</returns>
  38. public static Expression<Func<TDbObject, bool>> GetExpression(params KeyValuePair<string, object>[] keys)
  39. {
  40. var param = Expression.Parameter(typeof(TDbObject), "x");
  41. Expression totalExp = null;
  42. foreach (var pair in keys)
  43. {
  44. var equalExp = Expression.Equal(Expression.Property(param, pair.Key), Expression.Constant(pair.Value));
  45. totalExp = totalExp == null ? equalExp : Expression.And(equalExp, totalExp);
  46. }
  47. return Expression.Lambda<Func<TDbObject, bool>>(totalExp, param);
  48. }
  49. /// <summary>
  50. /// Execute SQL quries in try catch
  51. /// </summary>
  52. /// <param name="func">The queries to be performed</param>
  53. /// <returns>The result or an error</returns>
  54. public static OpResult<U> Execute<U>(Func<TEntities, DbSet<TDbObject>, OpResult<U>> func)
  55. {
  56. try
  57. {
  58. using (var db = new TEntities())
  59. {
  60. var table = GetTableStatic(db);
  61. return func(db, table);
  62. }
  63. }
  64. catch (Exception e)
  65. {
  66. return Logger.Error<U>(ResultStatus.DBError, e);
  67. }
  68. }
  69. }
  70. }