Last active
September 20, 2024 08:45
-
-
Save tshego3/928a9def8b1b58931b5ea90dbd8f446d to your computer and use it in GitHub Desktop.
Generate Blank SQL Select From C# Class Properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Reflection; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
var sql = GenerateBlankSelect<TestClass>(); | |
Console.WriteLine(sql); | |
} | |
public static string GenerateBlankSelect<T>() | |
{ | |
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); | |
var selectColumns = properties.Select(prop => | |
{ | |
var type = prop.PropertyType; | |
string blankValue; | |
if (type == typeof(string)) | |
blankValue = "''"; | |
else if (type == typeof(int)) | |
blankValue = "0"; | |
else if (type == typeof(Nullable<int>)) | |
blankValue = "0"; | |
else if (type == typeof(long)) | |
blankValue = "0"; | |
else if (type == typeof(Nullable<long>)) | |
blankValue = "0"; | |
else if (type == typeof(decimal)) | |
blankValue = "0"; | |
else if (type == typeof(Nullable<decimal>)) | |
blankValue = "0"; | |
else if (type == typeof(double)) | |
blankValue = "0"; | |
else if (type == typeof(short)) | |
blankValue = "0"; | |
else if (type == typeof(Int64)) | |
blankValue = "0"; | |
else if (type == typeof(DateTime)) | |
blankValue = "GETDATE()"; | |
else if (type == typeof(Nullable<System.DateTime>)) | |
blankValue = "GETDATE()"; | |
else if (type == typeof(Nullable<bool>)) | |
blankValue = "0"; | |
else | |
blankValue = "''"; // Fallback for other types | |
if (prop.Name == "PropFour" || prop.Name == "PropFive") | |
{ | |
blankValue = "'In progress'"; | |
} | |
return $"{blankValue} AS {prop.Name}"; | |
}); | |
return $"SELECT {string.Join(",", selectColumns)}"; | |
} | |
} | |
public class TestClass | |
{ | |
public string PropOne { get; set; | |
} | |
public int PropTwo { get; set; | |
} | |
public DateTime PropThree { get; set; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment