Skip to content

Instantly share code, notes, and snippets.

@EdgarValfogo
Last active February 28, 2020 19:50
Show Gist options
  • Save EdgarValfogo/a331116db39f80a89c16cdbcd6d8eedb to your computer and use it in GitHub Desktop.
Save EdgarValfogo/a331116db39f80a89c16cdbcd6d8eedb to your computer and use it in GitHub Desktop.
Method that creates a query string to INSERT INTO within the attributes
[AttributeUsage(AttributeTargets.Property)]
public class DataNamesAttribute : Attribute
{
protected List<string> _valueNames { get; set; }
public List<string> ValueNames
{
get
{
return _valueNames;
}
set
{
_valueNames = value;
}
}
protected bool _useToInsertQuery { get; set; } = true;
public bool useToInsertQuery
{
get
{
return _useToInsertQuery;
}
set
{
_useToInsertQuery = value;
}
}
public DataNamesAttribute()
{
_valueNames = new List<string>();
}
public DataNamesAttribute(params string[] valueNames)
{
_valueNames = valueNames.ToList();
}
public DataNamesAttribute(bool useToInsertQuery, params string[] valueNames)
{
_useToInsertQuery = useToInsertQuery;
_valueNames = valueNames.ToList();
}
}
public abstract class BaseData {
protected SqlCommand ProccessCreateQueryStringFromClass<T>(T obj, string table)
{
SqlCommand result = new SqlCommand("INSERT INTO {table} ");
List<string> columns = new List<string>();
List<string> values = new List<string>();
PropertyInfo[] props = obj.GetType().GetProperties();
foreach (PropertyInfo p in props)
{
DataNamesAttribute a = (DataNamesAttribute)p.GetCustomAttribute(typeof(DataNamesAttribute), true);
object propValue = p.GetValue(obj);
bool useToInsertQuery = a.useToInsertQuery;
if( ( p.PropertyType == typeof(DateTime?) || p.PropertyType == typeof(DateTime) ) && propValue != null )
{
if( (DateTime)propValue == DateTime.MinValue )
{
continue;
}
}
if (a == null || propValue == null || !useToInsertQuery) continue;
string columnName = a.ValueNames[0];
columns.Add(columnName);
string valueParameterReferenceName = "@" + p.Name;
values.Add(valueParameterReferenceName);
result.Parameters.AddWithValue(valueParameterReferenceName, propValue);
}
result.CommandText += $"({ String.Join(", ", columns)}) VALUES ({ String.Join(", ", values)})";
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment