Esempio n. 1
0
        public static void SetForeignKey <T>(this T @this, Guid?id = null) where T : IId
        {
            // Step 1. get a property with the SetForeignKeyAttribute
            foreach (PropertyInfo propertyInfo in @this.GetType().GetProperties())
            {
                // Set value
                if (propertyInfo.GetCustomAttribute <SetForeignKeyAttribute>() != null)
                {
                    // Set value
                    propertyInfo.SetValue(@this, @this.Id);
                }

                // Step in 1:1
                if (propertyInfo.PropertyType.GetInterfaces().Contains(typeof(IId)))
                {
                    IId child = propertyInfo.GetValue(@this) as IId;
                    if (child != null)
                    {
                        child.SetForeignKey(@this.Id);
                    }
                }

                // Step into collection 1:N
                if (propertyInfo.PropertyType.GetInterfaces().Contains(typeof(IEnumerable)))
                {
                    foreach (var item in propertyInfo.GetValue(@this) as IEnumerable)
                    {
                        IId child = item as IId;
                        if (child != null)
                        {
                            child.SetForeignKey(@this.Id);
                        }
                    }
                }
            }
        }