public static T ToObject <T>(TableRow tableRow) { PropertyInfo[] propertyInfos = typeof(T).GetProperties(); T target = Activator.CreateInstance <T>(); foreach (PropertyInfo pi in propertyInfos) { var piType = pi.PropertyType; var piName = pi.Name; object value = TypeServices.ChangeType(tableRow[piName], piType); pi.SetValue(target, value); } return(target); }
private static T Instance <T>(TableRow row, MappingBehaviour mappingBehaviour) where T : class, new() { Type type = typeof(T); if (!TypeMapping.ContainsType(type)) { TypeMapping.RegisterType <T>(); } var container = TypeMapping.GetTypeInfosContainer(type); switch (mappingBehaviour) { case MappingBehaviour.Loose: break; case MappingBehaviour.Strict: StringBuilder sb = new StringBuilder(); var headersExceptPropertyNames = row.Keys.Except(container.PropertyNames).ToArray(); if (headersExceptPropertyNames.Any()) { sb.AppendLine(); sb.AppendFormat( "** The following column(s) are present in the table row but not the target type '{0}': {1}", type.Name, headersExceptPropertyNames.JoinStrings()); } var propertyNamesExceptHeaders = container.PropertyNames.Except(row.Keys).ToArray(); if (propertyNamesExceptHeaders.Any()) { sb.AppendLine(); sb.AppendFormat( "** The following column(s) are present in the target type '{0}' but not in the table row: {1}", type.Name, propertyNamesExceptHeaders.JoinStrings()); } string message = sb.ToString(); if (!string.IsNullOrWhiteSpace(message)) { throw new MappingException(message); } break; default: throw new ArgumentOutOfRangeException(string.Format("Mapping behaviour '{0}' not managed", mappingBehaviour)); } var instance = Activator.CreateInstance <T>(); foreach (PropertyInfo propertyInfo in container.PropertyInfos) { object value = TypeServices.ChangeType(row[propertyInfo.Name], propertyInfo.PropertyType); propertyInfo.SetValue(instance, value); } //var instance = TypeServices.Resolve<T>(); //foreach (PropertyInfo propertyInfo in container.AllPropertyInfos) //{ // object value = TypeServices.ChangeType(row[propertyInfo.Name], propertyInfo.PropertyType); // propertyInfo.SetValue(instance, value); //} return(instance); }