Exemple #1
0
        public static object CleverConvertValue(object sourceValue, Type type)
        {
            if (IsNull(sourceValue, type))
            {
                return(null);
            }

            if (type.IsInstanceOfType(sourceValue))
            {
                return(sourceValue);
            }

            if (EnumerableTypeUtility.IsEnumerable(type))
            {
                Type  itemType = EnumerableTypeUtility.GetItemType(type);
                IList newList  = EnumerableTypeUtility.CreateList(itemType);

                CopyArrayItems((IEnumerable)sourceValue, itemType, newList);

                if (type.IsArray)
                {
                    Array array = Array.CreateInstance(itemType, newList.Count);
                    newList.CopyTo(array, 0);
                    return(array);
                }

                return(newList);
            }
            else
            {
                var newValue = Activator.CreateInstance(type);
                CopyProperties(sourceValue, newValue);
                return(newValue);
            }
        }
        private static void AddEmptyCollections(TEntity entity)
        {
            // EF Core doesn't create empty ICollection objects for the navigation properties, which causes errors in NavigationCollectionRepository.GetNavCollection.
            // This method adds all the empty collections. I'm not sure if Lazy-loading them is better, or if EF can add these itself when the entity is attached?

            foreach (PropertyInfo property in typeof(TEntity).GetProperties())
            {
                if (!EnumerableTypeUtility.IsEnumerable(property.PropertyType))
                {
                    continue;
                }

                if (property.GetValue(entity) != null)
                {
                    continue;
                }

                var itemType = EnumerableTypeUtility.GetItemType(property.PropertyType);
                var newList  = EnumerableTypeUtility.CreateList(itemType);

                property.SetValue(entity, newList);
            }
        }