Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public string GetInsertStatement<T>(List<T> items)
- {
- var result = string.Empty;
- var properties = typeof(T).GetProperties().Where(x => !x.GetGetMethod().IsVirtual).ToArray();
- var typeName = typeof(T).Name;
- foreach (var item in items)
- {
- result += $"INSERT INTO dbo.{typeName} ({string.Join(", ", properties.Select(x => x.Name))}) \n";
- result += $"Values(";
- for (int i = 0; i < properties.Count(); i++)
- {
- var prop = properties[i];
- if (prop.GetValue(item) == null)
- {
- result += "NULL";
- }
- else if (prop.PropertyType == typeof(string))
- {
- result += $"'{prop.GetValue(item)}'";
- }
- else if (prop.PropertyType == typeof(bool))
- {
- var value = (bool)prop.GetValue(item);
- result += value ? "1" : "0";
- }
- else if (prop.PropertyType == typeof(Guid) || prop.PropertyType == typeof(Guid?))
- {
- var key = ((Guid)prop.GetValue(item));
- if (key == Guid.Empty)
- result += $"'{Guid.NewGuid().ToString()}'";
- else
- result += $"'{key.ToString()}'";
- }
- else if(prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?))
- {
- result += $"'{((DateTime)prop.GetValue(item)).ToString()}'";
- }
- else if(prop.PropertyType == typeof(decimal) || prop.PropertyType == typeof(decimal?))
- {
- result += $"CAST({prop.GetValue(item)} AS DECIMAL(18, 6))";
- }
- else if(prop.PropertyType.IsEnum || (Nullable.GetUnderlyingType(prop.PropertyType)?.IsEnum ?? false))
- {
- result += $"{(int)prop.GetValue(item)}";
- }
- else
- {
- result += $"{prop.GetValue(item)}";
- }
- if(i < properties.Count() - 1)
- result += ", ";
- }
- result += ");\n";
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement