Ejemplo n.º 1
0
        /// <summary>
        /// Add an object to the list. For 1:n relations, any references on the object being added
        /// to the parent of the list will be updated to match the parents current values, and the
        /// object will be inserted if it is a new one. For n:m relations, a new relation object is
        /// created and inserted (the object itself is never persisted).
        /// </summary>
        /// <param name="transaction">The transaction within which to execute statements.</param>
        /// <param name="value">The object to add to the list</param>
        /// <param name="relatedObjects">A list of values to use when creating the n:m relation
        /// object.</param>
        /// <returns>The index of the newly added object</returns>
        public virtual int Add(Transaction transaction, object value, params object[] relatedObjects)
        {
            Check.VerifyNotNull(value, Error.NullParameter, "value");
            Check.Verify(containedMap.Type.Equals(value.GetType()) ||
                         value.GetType().IsSubclassOf(containedMap.Type),
                         Error.UnsupportedType, value.GetType());
            // skip adding objects matching existing data
            object val = Find(Key.GetKey(broker, true, value));

            value = val ?? value;
            // manage 1:n relation
            if (viaInstances == null)
            {
                Check.Verify(relatedObjects == null || relatedObjects.Length == 0,
                             Error.NotImplemented, "Request incompatible with GentleList in OneToMany mode.");
                // manage added object
                IPersistent obj = value as IPersistent;
                if (!obj.IsPersisted)
                {
                    // first we update the foreign key property on the added object
                    UpdateForeignKeyFields(value);
                    if (transaction != null)
                    {
                        transaction.Persist(obj);
                    }
                    else
                    {
                        obj.Persist();
                    }
                }
            }
            else
            {
                // manage n:m relation object - creates new relation object using parent and value
                object[] args = Merge(value, relatedObjects);
                viaInstances.Add(transaction, args);
            }
            // this bit ensures object uniqing by disallowing objects with identical PK
            // from being in the list more than once
            if (val == null)
            {
                return(base.Add(value));
            }
            else
            {
                return(IndexOf(val));
            }
        }