public static DataTable ToDataTable <T>(IEnumerable <T> models, String tableName) where T : class, new() { if (models == null || !models.Any()) { return(null); } else { DataTable result = new DataTable(tableName); IEnumerable <PropertyInfo> propertyInfos = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(ModelMapAttribute), true).Any()); //Create columns foreach (PropertyInfo propertyInfo in propertyInfos) { ModelMapAttribute attribute = propertyInfo.GetCustomAttributes(typeof(ModelMapAttribute), true).First() as ModelMapAttribute; if (!String.IsNullOrWhiteSpace(attribute.ColumnName)) { result.Columns.Add(attribute.ColumnName); } else { result.Columns.Add(propertyInfo.Name); } } //Fill the data foreach (var model in models) { int matchCount = 0; DataRow row = result.NewRow(); foreach (PropertyInfo propertyInfo in propertyInfos) { ModelMapAttribute attribute = propertyInfo.GetCustomAttributes(typeof(ModelMapAttribute), true).First() as ModelMapAttribute; Object value = propertyInfo.GetValue(model); row[!String.IsNullOrWhiteSpace(attribute.ColumnName) ? attribute.ColumnName : propertyInfo.Name] = value; if (value != null) { matchCount++; } } //Skip empty models if (matchCount > 0) { result.Rows.Add(row); } } result.AcceptChanges(); return(result); } }
public static List <SqlBulkCopyColumnMapping> GetColumnMapping <T>(this T entity) where T : class, new() { if (entity == null /*|| !entity.Any()*/) { return(null); } else { List <SqlBulkCopyColumnMapping> result = new List <SqlBulkCopyColumnMapping>(); IEnumerable <PropertyInfo> propertyInfos = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(ModelMapAttribute), false).Any()); //Dictionary<string, string> _dict = new Dictionary<string, string>(); //PropertyInfo[] props = typeof(T).GetProperties(); //foreach (PropertyInfo prop in props) //{ // object[] attrs = prop.GetCustomAttributes(true); // foreach (object attr in attrs) // { // ModelMapAttribute authAttr = attr as ModelMapAttribute; // if (authAttr != null) // { // string propName = prop.Name; // string auth = authAttr.ColumnName; // _dict.Add(propName, auth); // } // } //} //Create columns foreach (PropertyInfo propertyInfo in propertyInfos) { ModelMapAttribute attribute = propertyInfo.GetCustomAttributes(typeof(ModelMapAttribute), true).First() as ModelMapAttribute; if (!String.IsNullOrWhiteSpace(attribute.ColumnName)) { result.Add(new SqlBulkCopyColumnMapping(propertyInfo.Name, attribute.ColumnName)); } else { result.Add(new SqlBulkCopyColumnMapping(propertyInfo.Name, propertyInfo.Name)); } } return(result); } }