Assumes properties are decorated with [Column("column_name")]
attributes.
public static List<SqlParameter> ToSqlParameters<T>(this T obj)
{
var result = new List<SqlParameter>();
var properties = obj.GetType().GetProperties();
properties.ToList().ForEach(propertyInfo =>
{
var column = propertyInfo.GetCustomAttribute<ColumnAttribute>();
var notMapped = propertyInfo.GetCustomAttribute<NotMappedAttribute>();
// see previous post for this method "IsNullOrDefault"
if (column != null && notMapped = null && !propertyInfo.IsNullOrDefault(obj))
{
var fieldValue = propertyInfo.GetValue(obj, default);
var sqlParam = new SqlParameter($"@{column.Name}", fieldValue);
result.Add(sqlParam);
}
});
return result;
}