private static object HasMany(this IActiveRecord wrapper, FieldAttribute relationshipAttribute) { if (!(relationshipAttribute is RelationshipAttribute)) { throw new ActiveRecordAttributeException(wrapper.GetType(), "O atributo não é do tipo HasMany. Não foi possível retornar os objetos relacionados."); } HasManyAttribute hasMany = relationshipAttribute as HasManyAttribute; object[] customAttributes = hasMany.ClassType.GetCustomAttributes(typeof(RepositoryAttribute), true); if (customAttributes.Length != 1) { throw new ActiveRecordAttributeException(hasMany.ClassType, "Não foi possível encontrar o controlador da classe."); } RepositoryAttribute controlled = (RepositoryAttribute)customAttributes[0]; object relatedController = Activator.CreateInstance(controlled.ControllerType); if (relatedController == null) { throw new ActiveRecordAttributeException(controlled.ControllerType, "Não foi possível instanciar o controller."); } PrimaryFieldAttribute pkAtt = wrapper.GetPrimaryKeyDefinition(); if (pkAtt == null) { throw new ActiveRecordAttributeException(wrapper.GetType(), "Não foi possível encontrar a chave primária da classe."); } IQueryFilter filter = new QueryFilterClass(); filter.WhereClause = String.Format(pkAtt.QuoteValue ? "{0} = '{1}'" : "{0} = {1}", hasMany.FieldName, wrapper.UnderlyingObject.get_Value(pkAtt.Index)); if (!String.IsNullOrEmpty(hasMany.OrderBy)) { IQueryFilterDefinition definition = filter as IQueryFilterDefinition; definition.PostfixClause = hasMany.OrderBy; } // prepare the method for invoke // check if the method is lazy or not MethodInfo filterMethod = null; filterMethod = controlled.ControllerType.GetMethod(hasMany.Lazy ? "FilterLazy" : "Filter"); var parameters = new object[1]; parameters[0] = filter; // invoke and return return(filterMethod.Invoke(relatedController, parameters)); }
/// <summary> /// Retrieves the Primary Key attribute without the need to know /// the property name /// </summary> /// <param name="wrapper">IActiveRecord</param> /// <returns>PrimaryFieldAttribute</returns> public static PrimaryFieldAttribute GetPrimaryKeyDefinition(this IActiveRecord wrapper) { PrimaryFieldAttribute pkAttribute = null; var t = wrapper.GetType(); try { PropertyInfo[] properties = t.GetProperties(); foreach (PropertyInfo pi in properties) { object[] attributes = pi.GetCustomAttributes(typeof(PrimaryFieldAttribute), true); if (attributes.Length != 1) { continue; } pkAttribute = (PrimaryFieldAttribute)attributes[0]; break; } } catch (AmbiguousMatchException ambEx) { throw new ActiveRecordAttributeException( wrapper.GetType(), String.Format("A classe {0} possui dois ou mais atributos de chave primária.", t.Name), ambEx); } catch (ArgumentException argEx) { throw new ActiveRecordAttributeException( wrapper.GetType(), String.Format("A classe {0} não possui nenhum atributo de chave primária.", t.Name), argEx); } return(pkAttribute); }