Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. public string GetInsertStatement<T>(List<T> items)
  2. {
  3. var result = string.Empty;
  4. var properties = typeof(T).GetProperties().Where(x => !x.GetGetMethod().IsVirtual).ToArray();
  5. var typeName = typeof(T).Name;
  6. foreach (var item in items)
  7. {
  8.  
  9. result += $"INSERT INTO dbo.{typeName} ({string.Join(", ", properties.Select(x => x.Name))}) \n";
  10. result += $"Values(";
  11. for (int i = 0; i < properties.Count(); i++)
  12. {
  13. var prop = properties[i];
  14. if (prop.GetValue(item) == null)
  15. {
  16. result += "NULL";
  17. }
  18. else if (prop.PropertyType == typeof(string))
  19. {
  20. result += $"'{prop.GetValue(item)}'";
  21. }
  22. else if (prop.PropertyType == typeof(bool))
  23. {
  24. var value = (bool)prop.GetValue(item);
  25. result += value ? "1" : "0";
  26. }
  27. else if (prop.PropertyType == typeof(Guid) || prop.PropertyType == typeof(Guid?))
  28. {
  29. var key = ((Guid)prop.GetValue(item));
  30. if (key == Guid.Empty)
  31. result += $"'{Guid.NewGuid().ToString()}'";
  32. else
  33. result += $"'{key.ToString()}'";
  34. }
  35. else if(prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?))
  36. {
  37. result += $"'{((DateTime)prop.GetValue(item)).ToString()}'";
  38. }
  39. else if(prop.PropertyType == typeof(decimal) || prop.PropertyType == typeof(decimal?))
  40. {
  41. result += $"CAST({prop.GetValue(item)} AS DECIMAL(18, 6))";
  42. }
  43. else if(prop.PropertyType.IsEnum || (Nullable.GetUnderlyingType(prop.PropertyType)?.IsEnum ?? false))
  44. {
  45. result += $"{(int)prop.GetValue(item)}";
  46. }
  47. else
  48. {
  49. result += $"{prop.GetValue(item)}";
  50. }
  51.  
  52. if(i < properties.Count() - 1)
  53. result += ", ";
  54. }
  55.  
  56. result += ");\n";
  57. }
  58.  
  59.  
  60. return result;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement