//Checks to see if a related unique constraint exists
        //if it doesn't then a unique constraint is created.
        //if a unique constraint can't be created an exception will be thrown
        private void _ensureUniqueConstraintExists(ConstraintCollection collection,
                                                   DataColumn [] parentColumns)
        {
            //not null
            if (null == parentColumns)
            {
                throw new ArgumentNullException(
                          "ParentColumns can't be null");
            }

            UniqueConstraint uc = null;

            //see if unique constraint already exists
            //if not create unique constraint
            if (parentColumns[0] != null)
            {
                uc = UniqueConstraint.GetUniqueConstraintForColumnSet(parentColumns[0].Table.Constraints, parentColumns);
            }

            if (null == uc)
            {
                uc = new UniqueConstraint(parentColumns, false); //could throw
                parentColumns [0].Table.Constraints.Add(uc);
            }

            //keep reference
            _parentUniqueConstraint = uc;
            _parentUniqueConstraint.ChildConstraint = this;
        }
예제 #2
0
        internal override void AddToConstraintCollectionSetup(
            ConstraintCollection collection)
        {
            for (int i = 0; i < Columns.Length; i++)
            {
                if (Columns[i].Table != collection.Table)
                {
                    throw new ArgumentException("These columns don't point to this table.");
                }
            }
            //run Ctor rules again
            _validateColumns(_dataColumns);

            //make sure a unique constraint doesn't already exists for these columns
            UniqueConstraint uc = UniqueConstraint.GetUniqueConstraintForColumnSet(collection, this.Columns);

            if (null != uc)
            {
                throw new ArgumentException("Unique constraint already exists for these" +
                                            " columns. Existing ConstraintName is " + uc.ConstraintName);
            }

            //Allow only one primary key
            if (this.IsPrimaryKey)
            {
                uc = GetPrimaryKeyConstraint(collection);
                if (null != uc)
                {
                    uc._isPrimaryKey = false;
                }
            }

            // if constraint is based on one column only
            // this column becomes unique
            if (_dataColumns.Length == 1)
            {
                _dataColumns[0].SetUnique();
            }

            if (IsConstraintViolated())
            {
                throw new ArgumentException("These columns don't currently have unique values.");
            }

            _belongsToCollection = true;
        }