/// <summary> /// Adds the specified associated entities to the specified association member for the specified entity. /// </summary> /// <param name="entity">The entity</param> /// <param name="associationProperty">The association member (singleton or collection)</param> /// <param name="associatedEntities">Collection of associated entities</param> private static void SetAssociationMember(object entity, PropertyDescriptor associationProperty, IEnumerable <object> associatedEntities) { if (associatedEntities.Count() == 0) { return; } object associationValue = associationProperty.GetValue(entity); if (typeof(IEnumerable).IsAssignableFrom(associationProperty.PropertyType)) { if (associationValue == null) { throw Error.InvalidOperation(Resource.DataController_AssociationCollectionPropertyIsNull, associationProperty.ComponentType.Name, associationProperty.Name); } IList list = associationValue as IList; IEnumerable <object> associationSequence = null; MethodInfo addMethod = null; if (list == null) { // not an IList, so we have to use reflection Type associatedEntityType = TypeUtility.GetElementType(associationValue.GetType()); addMethod = associationValue.GetType().GetMethod("Add", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { associatedEntityType }, null); if (addMethod == null) { throw Error.InvalidOperation(Resource.DataController_InvalidCollectionMember, associationProperty.Name); } associationSequence = ((IEnumerable)associationValue).Cast <object>(); } foreach (object associatedEntity in associatedEntities) { // add the entity to the collection if it's not already there if (list != null) { if (!list.Contains(associatedEntity)) { list.Add(associatedEntity); } } else { if (!associationSequence.Contains(associatedEntity)) { addMethod.Invoke(associationValue, new object[] { associatedEntity }); } } } } else { // set the reference if it's not already set object associatedEntity = associatedEntities.Single(); object currentValue = associationProperty.GetValue(entity); if (!Object.Equals(currentValue, associatedEntity)) { associationProperty.SetValue(entity, associatedEntity); } } }