コード例 #1
0
        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);
        }
コード例 #2
0
 public static T CreateInstance <T>(this TableRow row, MappingBehaviour behaviour)
     where T : class, new()
 {
     return(Instance <T>(row, behaviour));
 }