benjaminvr

Untitled

Feb 14th, 2023
1,297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.36 KB | None | 0 0
  1. public abstract class QueryGenerationExperiment
  2. {
  3.     internal enum QueryOutputType
  4.     {
  5.         Object,
  6.         Id,
  7.         None
  8.     }
  9.  
  10.     private static List<Type> DefaultPermittedPropertyTypes = new()
  11.     {
  12.         typeof(bool), typeof(byte), typeof(Guid), typeof(int), typeof(long), typeof(byte[]), typeof(double),
  13.         typeof(decimal), typeof(DateTimeOffset), typeof(DateTime), typeof(char), typeof(string), typeof(float),
  14.         typeof(short), typeof(TimeSpan),
  15.     };
  16.  
  17.     internal string ProvideInsertQuery<T> (T instance,
  18.                                         QueryOutputType outputType=QueryOutputType.Object,
  19.                                         List<string>? omittedPropertyNames=null,
  20.                                         List<Type>? permittedPropertyTypes=null)
  21.                                         where T : Entity
  22.     {
  23.         List<string> defaultOmittedPropertyNames = new() { nameof(Entity.Id) };
  24.  
  25.         omittedPropertyNames ??= defaultOmittedPropertyNames;
  26.         permittedPropertyTypes ??= DefaultPermittedPropertyTypes;
  27.  
  28.         var tableName = nameof(T);
  29.         var propertyNames = typeof(T).GetProperties()
  30.                                      .Where(p => permittedPropertyTypes.Contains(p.PropertyType))
  31.                                      .Select(p => p.Name)
  32.                                      .Except(omittedPropertyNames);
  33.         var columnNames = propertyNames.Select(p => p.Length == 1 ? char.ToLower(p[0]).ToString() : char.ToLower(p[0]) + p[1..]);
  34.  
  35.         return $@"
  36.            INSERT INTO [dbo].[{tableName}]
  37.            ({
  38.                String.Join(", ", columnNames.Select(c => $"[{c}]"))
  39.            })
  40.            {
  41.                () =>
  42.                {
  43.                    switch (outputType)
  44.                    {
  45.                        case QueryOutputType.Object:
  46.                            return "OUTPUT INSERTED.*";
  47.                        case QueryOutputType.Id:
  48.                            return $"OUTPUT INSERTED.{nameof(Entity.Id)}";
  49.                        default:
  50.                        case QueryOutputType.None:
  51.                            return "";
  52.                    }
  53.                }
  54.            }
  55.            VALUES
  56.            ({
  57.                String.Join(", ", propertyNames.Select(p => $"@{p}"))
  58.            })
  59.            ;
  60.        ";
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment