79eeb762ba506703db3d07417d3f1b8dcb35cec5.svn-base 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data.Entity;
  5. using System.Data.Entity.Infrastructure;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Web;
  9. namespace iBemsDataService.Util
  10. {
  11. public class QueryManager<TModel> where TModel : class, new()
  12. {
  13. DbContext DbContext { get; set; }
  14. public QueryManager( DbContext dbContext )
  15. {
  16. this.DbContext = dbContext;
  17. }
  18. public bool Delete<TDbSet>( TDbSet dbSet , TModel model , bool isAttach = true )
  19. where TDbSet : DbSet<TModel>
  20. {
  21. try
  22. {
  23. if (isAttach) dbSet.Attach( model );
  24. dbSet.Remove( model );
  25. }
  26. catch( DbUpdateException )
  27. {
  28. throw;
  29. }
  30. return true;
  31. }
  32. public bool Delete<TDbSet>( TDbSet dbSet , IQueryable queryToDelete )
  33. where TDbSet : DbSet<TModel>
  34. {
  35. try
  36. {
  37. foreach( TModel deleteItem in queryToDelete )
  38. {
  39. dbSet.Remove( deleteItem );
  40. }
  41. }
  42. catch( DbUpdateException )
  43. {
  44. throw;
  45. }
  46. return true;
  47. }
  48. public bool DeleteAndInsert<TDbSet , TList>( TDbSet dbSet , TList list , IQueryable queryToDelete )
  49. where TDbSet : DbSet<TModel>
  50. where TList : IList
  51. {
  52. try
  53. {
  54. foreach( TModel deleteItem in queryToDelete )
  55. {
  56. dbSet.Remove( deleteItem );
  57. }
  58. //Type itemType = list.GetType().GetGenericTypeDefinition();
  59. PropertyInfo[] listItemProperties = null;
  60. var modelType = typeof( TModel );
  61. foreach( var item in list )
  62. {
  63. if (item == null)
  64. break;
  65. var model = new TModel();
  66. if ( listItemProperties == null )
  67. {
  68. listItemProperties = item.GetType().GetProperties();
  69. }
  70. foreach( var p in listItemProperties )
  71. {
  72. modelType.GetProperty( p.Name ).SetValue( model , p.GetValue( item ) );
  73. }
  74. dbSet.Add( model );
  75. }
  76. this.DbContext.SaveChanges();
  77. }
  78. catch( DbUpdateException )
  79. {
  80. //if( FmsWorkOrderToToFacilityExists( FmsWorkOrderToToFacility.SiteId ) )
  81. //{
  82. // return Conflict();
  83. //}
  84. //else
  85. {
  86. throw;
  87. }
  88. // return false;
  89. }
  90. return true;
  91. }
  92. }
  93. }