//Activate This Construntor to log All To Standard output
	//public TestClass():base(true){}

	//Activate this constructor to log Failures to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, false){}


	//Activate this constructor to log All to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, true){}

	//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES

	public void run()
	{
		Exception exp = null;

		DataSet ds = new DataSet();
		DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable();
		DataTable dtChild = GHTUtils.DataProvider.CreateChildDataTable();
		ds.Tables.Add(dtParent);
		ds.Tables.Add(dtChild);
		
		ForeignKeyConstraint fc = null;
		fc = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[0]);

		try
		{
			BeginCase("default ");
			Compare(fc.ConstraintName ,string.Empty );
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}

		fc.ConstraintName  = "myConstraint";

		try
		{
			BeginCase("set/get ");
			Compare(fc.ConstraintName ,"myConstraint" );
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}
	}
	//Activate This Construntor to log All To Standard output
	//public TestClass():base(true){}

	//Activate this constructor to log Failures to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, false){}


	//Activate this constructor to log All to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, true){}

	//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES

	public void run()
	{
		Exception exp = null;

		DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable();
		DataTable dtChild = GHTUtils.DataProvider.CreateChildDataTable();
		
		ForeignKeyConstraint fc = null;
		fc = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[0]);

		try
		{
			BeginCase("ToString - default");
			Compare(fc.ToString(), string.Empty );
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}

		fc = new ForeignKeyConstraint("myConstraint",dtParent.Columns[0],dtChild.Columns[0]);
		try
		{
			BeginCase("Tostring - Constraint name");
			Compare(fc.ToString(), "myConstraint");
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}	

	}
	//Activate This Construntor to log All To Standard output
	//public TestClass():base(true){}

	//Activate this constructor to log Failures to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, false){}


	//Activate this constructor to log All to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, true){}

	//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES

	public void run()
	{
		Exception exp = null;
		DataSet ds = new DataSet();
		DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable();
		DataTable dtChild = GHTUtils.DataProvider.CreateChildDataTable();
		ds.Tables.Add(dtParent);
		ds.Tables.Add(dtChild);
		dtParent.PrimaryKey = new DataColumn[] {dtParent.Columns[0]};
		ds.EnforceConstraints = true;

		ForeignKeyConstraint fc1,fc2;
		fc1 = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[0]);

		fc2 = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[1]);
		try
		{
			BeginCase("different columnn");
			Compare(fc1.Equals(fc2),false);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}

		//Two System.Data.ForeignKeyConstraint are equal if they constrain the same columns.
		try
		{
			BeginCase("same column");
			fc2 = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[0]);
			Compare(fc1.Equals(fc2),true);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}
	}
示例#4
0
        protected override void GenerateForeignKey(System.Data.ForeignKeyConstraint fk)
        {
            StringWriter tw = new StringWriter();

            tw.WriteLine("ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY (",
                         formatTableName(fk.Table),
                         fk.ConstraintName
                         );

            GenerateColumnList(tw, fk.Columns);

            tw.WriteLine("REFERENCES {0} (",
                         formatTableName(fk.RelatedTable)
                         );

            GenerateColumnList(tw, fk.RelatedColumns);

            if (fk.DeleteRule == Rule.Cascade)
            {
                tw.WriteLine("ON DELETE CASCADE");
            }
            else if (fk.DeleteRule == Rule.None)
            {
                tw.WriteLine("ON DELETE NO ACTION");
            }
            if (fk.UpdateRule == Rule.Cascade)
            {
                tw.WriteLine("ON UPDATE CASCADE");
            }
            else if (fk.UpdateRule == Rule.None)
            {
                tw.WriteLine("ON UPDATE NO ACTION");
            }
            this.Admin.ExecuteNonQuery(ConnectionString, tw.ToString());
        }
	//Activate This Construntor to log All To Standard output
	//public TestClass():base(true){}

	//Activate this constructor to log Failures to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, false){}


	//Activate this constructor to log All to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, true){}

	//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES

	public void run()
	{
		Exception exp = null;

		DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable();
		DataTable dtChild = GHTUtils.DataProvider.CreateChildDataTable();
		
		ForeignKeyConstraint fc = null;
		fc = new ForeignKeyConstraint("myForeignKey",dtParent.Columns[0],dtChild.Columns[0]);

		try
		{
			BeginCase("Ctor");
			Compare(fc == null ,false );
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}

		try
		{
			BeginCase("Ctor - name");
			Compare(fc.ConstraintName  ,"myForeignKey" );
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}
	}
	//Activate This Construntor to log All To Standard output
	//public TestClass():base(true){}

	//Activate this constructor to log Failures to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, false){}


	//Activate this constructor to log All to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, true){}

	//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES

	public void run()
	{
		Exception exp = null;
		//int RowCount;
		DataSet ds = new DataSet();
		DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable();
		DataTable dtChild = GHTUtils.DataProvider.CreateChildDataTable();
		ds.Tables.Add(dtParent);
		ds.Tables.Add(dtChild);
		
		ForeignKeyConstraint fc = null;
		fc = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[0]);

		try
		{
			BeginCase("Columns");
			Compare(fc.Columns[0]  ,dtChild.Columns[0] );
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}

		try
		{
			BeginCase("Columns count");
			Compare(fc.Columns.Length ,1 );
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}
	}
	//Activate This Construntor to log All To Standard output
	//public TestClass():base(true){}

	//Activate this constructor to log Failures to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, false){}


	//Activate this constructor to log All to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, true){}

	//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES

	public void run()
	{
		Exception exp = null;

		DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable();
		DataTable dtChild = GHTUtils.DataProvider.CreateParentDataTable();
		
		ForeignKeyConstraint fc = null;
		fc = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[0]);

		PropertyCollection pc = fc.ExtendedProperties ;
        
		try
		{
			base.BeginCase("Checking ExtendedProperties default ");
			base.Compare(fc != null,true);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}
		

		try
		{
			base.BeginCase("Checking ExtendedProperties count ");
			base.Compare(pc.Count ,0);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}
	}
示例#8
0
 private void InitClass()
 {
     this.DataSetName        = "dsPublishers";
     this.Prefix             = "";
     this.Namespace          = "Deverest.Generated.DataSets";
     this.Locale             = new System.Globalization.CultureInfo("en-US");
     this.CaseSensitive      = false;
     this.EnforceConstraints = true;
     System.Data.ForeignKeyConstraint fkc;
     this.tablepublishers = new publishersDataTable();
     this.Tables.Add(this.tablepublishers);
     this.tabletitles = new titlesDataTable();
     this.Tables.Add(this.tabletitles);
     fkc = new System.Data.ForeignKeyConstraint("publisherstitles", new System.Data.DataColumn[] {
         this.tablepublishers.pub_idColumn,
         this.tablepublishers.pub_nameColumn
     }, new System.Data.DataColumn[] {
         this.tabletitles.titlepub_idColumn,
         this.tabletitles.titleColumn
     });
     this.tabletitles.Constraints.Add(fkc);
     fkc.AcceptRejectRule          = System.Data.AcceptRejectRule.None;
     fkc.DeleteRule                = System.Data.Rule.Cascade;
     fkc.UpdateRule                = System.Data.Rule.Cascade;
     this.relationpublisherstitles = new System.Data.DataRelation("publisherstitles", new System.Data.DataColumn[] {
         this.tablepublishers.pub_idColumn,
         this.tablepublishers.pub_nameColumn
     }, new System.Data.DataColumn[] {
         this.tabletitles.titlepub_idColumn,
         this.tabletitles.titleColumn
     });
     this.relationpublisherstitles.Nested = true;
     this.Relations.Add(this.relationpublisherstitles);
     this.tabletitleauthors = new titleauthorsDataTable();
     this.Tables.Add(this.tabletitleauthors);
     fkc = new System.Data.ForeignKeyConstraint("titlestitleauthors", new System.Data.DataColumn[] {
         this.tabletitles.title_idColumn
     }, new System.Data.DataColumn[] {
         this.tabletitleauthors.title_idColumn
     });
     this.tabletitleauthors.Constraints.Add(fkc);
     fkc.AcceptRejectRule            = System.Data.AcceptRejectRule.None;
     fkc.DeleteRule                  = System.Data.Rule.Cascade;
     fkc.UpdateRule                  = System.Data.Rule.Cascade;
     this.relationtitlestitleauthors = new System.Data.DataRelation("titlestitleauthors", new System.Data.DataColumn[] {
         this.tabletitles.title_idColumn
     }, new System.Data.DataColumn[] {
         this.tabletitleauthors.title_idColumn
     });
     this.relationtitlestitleauthors.Nested = true;
     this.Relations.Add(this.relationtitlestitleauthors);
 }
示例#9
0
    public static void AddForeignKeyConstraint( DataSet ds )
    {
        DataColumn            parent = ds.Tables["Categories"].Columns["CategoryID"] ;
        DataColumn            child  = ds.Tables["Products"].Columns["CategoryID"] ;

        ForeignKeyConstraint  fk = new ForeignKeyConstraint ( "FK_Product_CategoryID" , parent , child ) ;

        fk.UpdateRule = Rule.Cascade ;
        fk.DeleteRule = Rule.SetNull ;

        // Create the constraint
        // If this fails, you have a row in the products table with no associated category
        ds.Tables["Products"].Constraints.Add ( fk ) ;
    }
示例#10
0
        private void button5_Click(object sender, System.EventArgs e)
        {
            //创建外键约束
            System.Data.ForeignKeyConstraint fkNew;

            fkNew = new System.Data.ForeignKeyConstraint("MyFK", this.dsUntyped.Tables["dtMain"].Columns["MainID"], this.dsUntyped.Tables["dtSecond"].Columns["MainLink"]);
            //添加外键约束
            this.dsUntyped.Tables["dtSecond"].Constraints.Add(fkNew);

            string strMessage;

            strMessage  = "新的约束名称为:  ";
            strMessage += this.dsUntyped.Tables["dtSecond"].Constraints[0].ConstraintName.ToString();
            MessageBox.Show(strMessage);
        }
 internal DesignRelation this[ForeignKeyConstraint constraint]
 {
     get
     {
         if (constraint != null)
         {
             foreach (DesignRelation relation in this)
             {
                 if (relation.ForeignKeyConstraint == constraint)
                 {
                     return relation;
                 }
             }
         }
         return null;
     }
 }
示例#12
0
        static void Main(string[] args)
        {
            DataSet shopDB = new DataSet("ShopDB");
            DataTable orders = new DataTable("Orders");
            DataTable customers = new DataTable("Customers");

            string conStr = @"Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=ShopDB; Integrated Security=True;"; // создание строки подключения

            using (SqlConnection connection = new SqlConnection(conStr))
            {
                connection.Open();

                SqlCommand customersCmd = new SqlCommand("SELECT CustomerNo, LName, FName, Address1, Phone FROM Customers", connection);
                SqlCommand ordersCmd = new SqlCommand("SELECT OrderID, CustomerNo, OrderDate FROM Orders", connection);

                SqlDataReader ordersReader = ordersCmd.ExecuteReader(); // получение DataReader для таблицы OrderDetails

                // метод LoadWithSchema позволяет на основе объекта DataReader создать объект DataTable 
                //с ограничениями для столбцов как в базе данных и заполнить эту таблицу данными
                orders.LoadWithSchema(ordersReader);
                ordersReader.Close();

                SqlDataReader customersReader = customersCmd.ExecuteReader();
                customers.LoadWithSchema(customersReader);
                customersReader.Close();
            }







            customers.PrimaryKey = new DataColumn[] { customers.Columns[0] };

            shopDB.Tables.AddRange(new DataTable[] { customers, orders });
            // создание ограничения ForeignKeyConstraint для таблицы OrderDetails
            var FK_CustomersOrders = new ForeignKeyConstraint(customers.Columns["CustomerNo"], orders.Columns["CustomerNo"]);
            orders.Constraints.Add(FK_CustomersOrders);

            

            
            
            Console.ReadKey();
        }
示例#13
0
		[Test] public void Columns()
		{
			//int RowCount;
			DataSet ds = new DataSet();
			DataTable dtParent = DataProvider.CreateParentDataTable();
			DataTable dtChild = DataProvider.CreateChildDataTable();
			ds.Tables.Add(dtParent);
			ds.Tables.Add(dtChild);

			ForeignKeyConstraint fc = null;
			fc = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[0]);

			// Columns
			Assert.AreEqual(dtChild.Columns[0] , fc.Columns[0]  , "FKC1");

			// Columns count
			Assert.AreEqual(1 , fc.Columns.Length , "FKC2");
		}
        public ForeignKeyProviderBase(ITablePopulator foreignTable, ForeignKeyConstraint foreignKey)
        {
            if (foreignTable == null)
                throw new ArgumentNullException("foreignTable");
            if (foreignKey == null)
                throw new ArgumentNullException("foreignKey");
            this.foreignTable = foreignTable;
            this.foreignKey = foreignKey;

            isNullable = true;
            foreach (DataColumn column in foreignKey.Columns)
            {
                if (!column.AllowDBNull)
                {
                    isNullable = false;
                    break;
                }
            }
        }
示例#15
0
 public IForeignKeyProvider this[System.Data.ForeignKeyConstraint foreignKey]
 {
     get
     {
         return((IForeignKeyProvider)this.contraints[foreignKey]);
     }
     set
     {
         if (foreignKey == null)
         {
             throw new ArgumentNullException("foreignKey");
         }
         if (value == null)
         {
             throw new ArgumentNullException("value");
         }
         this.contraints[foreignKey] = value;
     }
 }
示例#16
0
        private ForeignKeyConstraint FindForeignKey(ConstraintCollection cl)
        {
            ForeignKeyConstraint fkc = null;

            foreach (Constraint o in cl)
            {
                if (!(o is ForeignKeyConstraint))
                {
                    continue;
                }
                fkc = (ForeignKeyConstraint)o;
                /* Check ChildColumns & ParentColumns */
                if (CompareDataColumns(ChildColumns, fkc.Columns) &&
                    CompareDataColumns(ParentColumns, fkc.RelatedColumns))
                {
                    return(fkc);
                }
            }
            return(null);
        }
        public override bool Equals(object key)
        {
            ForeignKeyConstraint fkc = key as ForeignKeyConstraint;

            if (null == fkc)
            {
                return(false);
            }

            //if the fk constrains the same columns then they are equal
            if (!DataColumn.AreColumnSetsTheSame(this.RelatedColumns, fkc.RelatedColumns))
            {
                return(false);
            }
            if (!DataColumn.AreColumnSetsTheSame(this.Columns, fkc.Columns))
            {
                return(false);
            }

            return(true);
        }
示例#18
0
        internal ForeignKeyConstraint?Clone(DataTable destination)
        {
            Debug.Assert(Table == RelatedTable, "We call this clone just if we have the same datatable as parent and child ");
            int keys = Columns.Length;

            DataColumn[] columns        = new DataColumn[keys];
            DataColumn[] relatedColumns = new DataColumn[keys];

            for (int i = 0; i < keys; i++)
            {
                DataColumn src   = Columns[i];
                int        iDest = destination.Columns.IndexOf(src.ColumnName);
                if (iDest < 0)
                {
                    return(null);
                }
                columns[i] = destination.Columns[iDest];

                src   = RelatedColumnsReference[i];
                iDest = destination.Columns.IndexOf(src.ColumnName);
                if (iDest < 0)
                {
                    return(null);
                }
                relatedColumns[i] = destination.Columns[iDest];
            }
            ForeignKeyConstraint clone = new ForeignKeyConstraint(ConstraintName, relatedColumns, columns);

            clone.UpdateRule       = UpdateRule;
            clone.DeleteRule       = DeleteRule;
            clone.AcceptRejectRule = AcceptRejectRule;

            // ...Extended Properties
            foreach (object key in ExtendedProperties.Keys)
            {
                clone.ExtendedProperties[key] = ExtendedProperties[key];
            }

            return(clone);
        }
		public void Ctor1 ()
		{
			DataTable Table =  _ds.Tables [0];
			
			AssertEquals ("test#01", 0, Table.Constraints.Count);
			Table =  _ds.Tables [1];
			AssertEquals ("test#02", 0, Table.Constraints.Count);
			
			// ctor (string, DataColumn, DataColumn
			ForeignKeyConstraint Constraint = new ForeignKeyConstraint ("test", _ds.Tables [0].Columns [2], _ds.Tables [1].Columns [0]);
			Table = _ds.Tables [1];
			Table.Constraints.Add (Constraint);
			
			AssertEquals ("test#03", 1, Table.Constraints.Count);
			AssertEquals ("test#04", "test", Table.Constraints [0].ConstraintName);
			AssertEquals ("test#05", typeof (ForeignKeyConstraint), Table.Constraints [0].GetType ());

			Table = _ds.Tables [0];
			AssertEquals ("test#06", 1, Table.Constraints.Count);
			AssertEquals ("test#07", "Constraint1", Table.Constraints [0].ConstraintName);
			AssertEquals ("test#08", typeof (UniqueConstraint), Table.Constraints [0].GetType ());
		}
示例#20
0
		[Test] public void Equals()
		{
			DataSet ds = new DataSet();
			DataTable dtParent = DataProvider.CreateParentDataTable();
			DataTable dtChild = DataProvider.CreateChildDataTable();
			ds.Tables.Add(dtParent);
			ds.Tables.Add(dtChild);
			dtParent.PrimaryKey = new DataColumn[] {dtParent.Columns[0]};
			ds.EnforceConstraints = true;

			ForeignKeyConstraint fc1,fc2;
			fc1 = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[0]);

			fc2 = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[1]);
			// different columnn
			Assert.AreEqual(false, fc1.Equals(fc2), "FKC3");

			//Two System.Data.ForeignKeyConstraint are equal if they constrain the same columns.
			// same column
			fc2 = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[0]);
			Assert.AreEqual(true, fc1.Equals(fc2), "FKC4");
		}
		public void Ctor1 ()
		{
			DataTable Table =  _ds.Tables [0];
			
			Assert.AreEqual (0, Table.Constraints.Count, "test#01");
			Table =  _ds.Tables [1];
			Assert.AreEqual (0, Table.Constraints.Count, "test#02");
			
			// ctor (string, DataColumn, DataColumn
			ForeignKeyConstraint Constraint = new ForeignKeyConstraint ("test", _ds.Tables [0].Columns [2], _ds.Tables [1].Columns [0]);
			Table = _ds.Tables [1];
			Table.Constraints.Add (Constraint);
			
			Assert.AreEqual (1, Table.Constraints.Count, "test#03");
			Assert.AreEqual ("test", Table.Constraints [0].ConstraintName, "test#04");
			Assert.AreEqual (typeof (ForeignKeyConstraint), Table.Constraints [0].GetType (), "test#05");

			Table = _ds.Tables [0];
			Assert.AreEqual (1, Table.Constraints.Count, "test#06");
			Assert.AreEqual ("Constraint1", Table.Constraints [0].ConstraintName, "test#07");
			Assert.AreEqual (typeof (UniqueConstraint), Table.Constraints [0].GetType (), "test#08");
		}
示例#22
0
        internal ForeignKeyConstraint Clone(DataTable destination)
        {
            int length = this.Columns.Length;

            DataColumn[] childColumns  = new DataColumn[length];
            DataColumn[] parentColumns = new DataColumn[length];
            int          index         = 0;

            for (int i = 0; i < length; i++)
            {
                DataColumn column = this.Columns[i];
                index = destination.Columns.IndexOf(column.ColumnName);
                if (index < 0)
                {
                    return(null);
                }
                childColumns[i] = destination.Columns[index];
                column          = this.RelatedColumnsReference[i];
                index           = destination.Columns.IndexOf(column.ColumnName);
                if (index < 0)
                {
                    return(null);
                }
                parentColumns[i] = destination.Columns[index];
            }
            ForeignKeyConstraint constraint = new ForeignKeyConstraint(this.ConstraintName, parentColumns, childColumns)
            {
                UpdateRule       = this.UpdateRule,
                DeleteRule       = this.DeleteRule,
                AcceptRejectRule = this.AcceptRejectRule
            };

            foreach (object obj2 in base.ExtendedProperties.Keys)
            {
                constraint.ExtendedProperties[obj2] = base.ExtendedProperties[obj2];
            }
            return(constraint);
        }
        // check if a table can be removed from this collectiuon.
        // if the table can not be remved act according to throwException parameter.
        // if it is true throws an Exception, else return false.
        private bool CanRemove(DataTable table, bool throwException)
        {
            // check if table is null reference
            if (table == null)
            {
                if (throwException)
                {
                    throw new ArgumentNullException("table");
                }
                return(false);
            }

            // check if the table has the same DataSet as this collection.
            if (table.DataSet != this.dataSet)
            {
                if (!throwException)
                {
                    return(false);
                }
                throw new ArgumentException("Table " + table.TableName + " does not belong to this DataSet.");
            }

            // check the table has a relation attached to it.
            if (table.ParentRelations.Count > 0 || table.ChildRelations.Count > 0)
            {
                if (!throwException)
                {
                    return(false);
                }
                throw new ArgumentException("Cannot remove a table that has existing relations. Remove relations first.");
            }

            // now we check if any ForeignKeyConstraint is referncing 'table'.
            foreach (Constraint c in table.Constraints)
            {
                UniqueConstraint uc = c as UniqueConstraint;
                if (uc != null)
                {
                    if (uc.ChildConstraint == null)
                    {
                        continue;
                    }

                    if (!throwException)
                    {
                        return(false);
                    }
                    RaiseForeignKeyReferenceException(table.TableName, uc.ChildConstraint.ConstraintName);
                }

                ForeignKeyConstraint fc = c as ForeignKeyConstraint;
                if (fc == null)
                {
                    continue;
                }

                if (!throwException)
                {
                    return(false);
                }
                RaiseForeignKeyReferenceException(table.TableName, fc.ConstraintName);
            }

            return(true);
        }
 public DesignRelation(System.Data.ForeignKeyConstraint foreignKeyConstraint)
 {
     this.DataRelation             = null;
     this.dataForeignKeyConstraint = foreignKeyConstraint;
 }
示例#25
0
		public void AddFkException2 ()
		{
			//Foreign key rules only work when the tables
			//are apart of the dataset
			DataSet ds = new DataSet ();
			ds.Tables.Add (_table);
			_table2.TableName = "TestTable2";
			ds.Tables.Add (_table2);

			_table.Rows.Add (new object [] {1});
			
			// will need a matching parent value in 
			// _table
			_table2.Rows.Add (new object [] {3}); 
								

			//FKC: no matching parent value
			try {
				ForeignKeyConstraint fkc = new ForeignKeyConstraint (_table.Columns [0],
					_table2.Columns [0]);
				
				_table2.Constraints.Add (fkc);	//should throw			
				Assert.Fail ("B1: Failed to throw ArgumentException.");
			} catch (ArgumentException) {
			} catch (AssertionException exc) {
				throw exc;
			} catch (Exception exc) {
				Assert.Fail ("A1: Wrong Exception type. " + exc.ToString ());
			}
		}
示例#26
0
        internal ForeignKeyConstraint Clone(DataTable destination) {
            Debug.Assert(this.Table == this.RelatedTable, "We call this clone just if we have the same datatable as parent and child ");
            int keys = Columns.Length;
            DataColumn[] columns = new DataColumn[keys];
            DataColumn[] relatedColumns = new DataColumn[keys];

            int iDest  =0;

            for (int i = 0; i < keys; i++) {
                DataColumn src = Columns[i];
                iDest = destination.Columns.IndexOf(src.ColumnName);
                if (iDest < 0)
                    return null;
                columns[i] = destination.Columns[iDest];

                src = RelatedColumnsReference[i];
                iDest = destination.Columns.IndexOf(src.ColumnName);
                if (iDest < 0)
                    return null;
                relatedColumns[i] = destination.Columns[iDest];
            }
            ForeignKeyConstraint clone = new ForeignKeyConstraint(ConstraintName, relatedColumns, columns);
            clone.UpdateRule = this.UpdateRule;
            clone.DeleteRule = this.DeleteRule;
            clone.AcceptRejectRule = this.AcceptRejectRule;

            // ...Extended Properties
            foreach(Object key in this.ExtendedProperties.Keys) {
                clone.ExtendedProperties[key]=this.ExtendedProperties[key];
            }

            return clone;
        }
示例#27
0
		Constraint Add (string name, DataColumn primaryKeyColumn, DataColumn foreignKeyColumn)
		{
			ForeignKeyConstraint fc = new ForeignKeyConstraint (name, primaryKeyColumn, foreignKeyColumn);
			Add (fc);
			return fc;
		}
示例#28
0
        private void CopyRelations(DataSet Copy)
        {
            //Creation of the relation contains some of the properties, and the constructor
            //demands these values. instead changing the DataRelation constructor and behaviour the
            //parameters are pre-configured and sent to the most general constructor

            foreach (DataRelation MyRelation in this.Relations)
            {
                // typed datasets create relations through ctor.
                if (Copy.Relations.Contains(MyRelation.RelationName))
                {
                    continue;
                }

                string       pTable = MyRelation.ParentTable.TableName;
                string       cTable = MyRelation.ChildTable.TableName;
                DataColumn[] P_DC   = new DataColumn[MyRelation.ParentColumns.Length];
                DataColumn[] C_DC   = new DataColumn[MyRelation.ChildColumns.Length];
                int          i      = 0;

                foreach (DataColumn DC in MyRelation.ParentColumns)
                {
                    P_DC[i] = Copy.Tables[pTable].Columns[DC.ColumnName];
                    i++;
                }

                i = 0;

                foreach (DataColumn DC in MyRelation.ChildColumns)
                {
                    C_DC[i] = Copy.Tables[cTable].Columns[DC.ColumnName];
                    i++;
                }

                DataRelation cRel = new DataRelation(MyRelation.RelationName, P_DC, C_DC, false);
                Copy.Relations.Add(cRel);
            }

            // Foreign Key constraints are not cloned in DataTable.Clone
            // so, these constraints should be cloned when copying the relations.
            foreach (DataTable table in this.Tables)
            {
                foreach (Constraint c in table.Constraints)
                {
                    if (!(c is ForeignKeyConstraint) ||
                        Copy.Tables[table.TableName].Constraints.Contains(c.ConstraintName))
                    {
                        continue;
                    }
                    ForeignKeyConstraint fc          = (ForeignKeyConstraint)c;
                    DataTable            parentTable = Copy.Tables [fc.RelatedTable.TableName];
                    DataTable            currTable   = Copy.Tables [table.TableName];
                    DataColumn[]         parentCols  = new DataColumn [fc.RelatedColumns.Length];
                    DataColumn[]         childCols   = new DataColumn [fc.Columns.Length];
                    for (int j = 0; j < parentCols.Length; ++j)
                    {
                        parentCols [j] = parentTable.Columns[fc.RelatedColumns[j].ColumnName];
                    }
                    for (int j = 0; j < childCols.Length; ++j)
                    {
                        childCols [j] = currTable.Columns[fc.Columns[j].ColumnName];
                    }
                    currTable.Constraints.Add(fc.ConstraintName, parentCols, childCols);
                }
            }
        }
示例#29
0
	public void Constraint_Relations_Test2 ()
	{
		//Serialize DataSet
		DataSet ds = new DataSet ();
		
		DataTable tb1 = new DataTable ();
		tb1.Columns.Add ("id", typeof (int));
		tb1.Columns.Add ("name", typeof (string));
		tb1.Rows.Add (new object[] {1, "A"});
		tb1.Rows.Add (new object[] {2, "B"});
		ds.Tables.Add (tb1);
		//Table2
		DataTable tb2 = new DataTable ();
		tb2.Columns.Add ("eid", typeof (int));
		tb2.Columns.Add ("SSN", typeof (int));
		tb2.Columns.Add ("DOJ", typeof (DateTime));
		tb2.Rows.Add (new object[] {1, 111, "07-25-06"});
		tb2.Rows.Add (new object[] {2, 112, "07-19-06"});
		tb2.Rows.Add (new object[] {3, 113, "07-22-06"});
		ds.Tables.Add (tb2);
		//Table3
		DataTable tb3 = new DataTable ();
		tb3.Columns.Add ("eid", typeof (int));
		tb3.Columns.Add ("Salary", typeof (long));
		tb3.Rows.Add (new object[] {1, 20000});
		tb3.Rows.Add (new object[] {2, 30000});
		ds.Tables.Add (tb3);
		//Table4
		DataTable tb4 = new DataTable ();
		tb4.Columns.Add ("ssn", typeof (int));
		tb4.Columns.Add ("Name", typeof (string));
		tb4.Columns.Add ("DOB", typeof (DateTime));
		tb4.Rows.Add (new object[] {112, "A", "09-12-81"});
		tb4.Rows.Add (new object[] {113, "B", "09-12-82"});
		ds.Tables.Add (tb4);
		
		//Constraints
		UniqueConstraint uKey = new UniqueConstraint (tb1.Columns ["id"]);
		/*
		DataColumn[] parentColumns = new DataColumn[2];
		parentColumns[0] = tb1.Columns["id"];
		parentColumns[1] = tb1.Columns["name"];
		DataColumn[] childColumns = new DataColumn[2];
		childColumns[0] = tb4.Columns["ssn"];
		childColumns[1] = tb4.Columns["Name"];
		ForeignKeyConstraint fKey1 = new ForeignKeyConstraint(childColumns,
								      parentColumns);
		*/
		ForeignKeyConstraint fKey1 = new ForeignKeyConstraint (tb2.Columns ["eid"], 
									tb1.Columns ["id"]);
		ForeignKeyConstraint fKey2 = new ForeignKeyConstraint (tb2.Columns ["eid"], 
									tb3.Columns ["eid"]);
		DataRelation rel = new DataRelation ("Relation1", tb1.Columns ["name"], tb4.Columns ["Name"]);
		DataRelation rel1 = new DataRelation ("Relation2", tb2.Columns ["SSN"], tb4.Columns ["ssn"]);
		tb1.Constraints.Add (uKey);	
		tb1.Constraints.Add (fKey1);
		tb3.Constraints.Add (fKey2);
		ds.Relations.Add (rel);
		ds.Relations.Add (rel1);
		ds.AcceptChanges();

		//SerializeDataSet
		BinaryFormatter bf = new BinaryFormatter ();
		ds.RemotingFormat = SerializationFormat.Binary;
		FileStream fs = new FileStream ("Test/System.Data/binserialize/BS-tb5.bin", FileMode.Open, FileAccess.Read);
		BinaryReader r = new BinaryReader (fs);
		byte [] serializedStream = r.ReadBytes ((int)fs.Length);
		r.Close ();
		fs.Close ();
		//DserializeDataSet
		MemoryStream ms = new MemoryStream (serializedStream);
		DataSet ds1 = (DataSet)bf.Deserialize (ms);
		ms.Close ();
		Assert.AreEqual (ds.Tables.Count, ds1.Tables.Count, "#1 Number of Table differs");
		//Test Constraints
		//Table1
		Assert.AreEqual (ds.Tables [0].Constraints.Count, ds1.Tables [0].Constraints.Count, "#2 Number of Constraints differs in Table :{0}", ds.Tables [0]);
		for (int i = 0; i < ds.Tables [0].Constraints.Count; i++)
			Assert.AreEqual (ds.Tables [0].Constraints [i].GetType (), 
					 ds1.Tables [0].Constraints [i].GetType (), 
					 "#3 Constraint : {0} is Different", ds.Tables [0].Constraints [i]);
		//Table2
		Assert.AreEqual (ds.Tables [1].Constraints.Count, ds1.Tables [1].Constraints.Count, "#4 Number of Constraints differs in Table :{0}", ds.Tables [1]);
		for (int i = 0; i < ds.Tables [1].Constraints.Count; i++)
			Assert.AreEqual (ds.Tables [1].Constraints [i].GetType (), 
					 ds1.Tables [1].Constraints [i].GetType (), 
					 "#5 Constraint : {0} is Different", ds.Tables [1].Constraints [i]);
		//Table3
		Assert.AreEqual (ds.Tables [2].Constraints.Count, ds1.Tables [2].Constraints.Count, "#5 Number of Constraints differs in Table :{0}", ds.Tables [2]);
		for (int i = 0; i < ds.Tables [2].Constraints.Count; i++)
			Assert.AreEqual (ds.Tables [2].Constraints [i].GetType (), 
					 ds1.Tables [2].Constraints [i].GetType (), 
					 "#6 Constraint : {0} is Different", ds.Tables [2].Constraints [i]);
		//Table4
		Assert.AreEqual (ds.Tables [3].Constraints.Count, ds1.Tables [3].Constraints.Count, "#7 Number of Constraints differs in Table :{0}", ds.Tables [3]);
		for (int i = 0; i < ds.Tables [3].Constraints.Count; i++) 
			Assert.AreEqual (ds.Tables [3].Constraints [i].GetType (), 
					 ds1.Tables [3].Constraints [i].GetType (), 
					 "#8 Constraint : {0} is Different", ds.Tables [3].Constraints [i]);
		//Relations
		Assert.AreEqual (ds.Relations.Count, ds1.Relations.Count, "#8 Number of realtions differ");
		for (int i = 0; i < ds.Relations.Count; i++)
			Assert.AreEqual (ds.Relations [i].RelationName, ds.Relations [i].RelationName, "#9 Relation : {0} differs", ds.Relations [i]);
	}
示例#30
0
/*
        Deserialize the constraints on the table.
        ***Schema for Serializing ArrayList of Constraints***
        Unique Constraint - ["U"]->[constraintName]->[columnIndexes]->[IsPrimaryKey]->[extendedProperties]
        Foriegn Key Constraint - ["F"]->[constraintName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[AcceptRejectRule, UpdateRule, DeleteRule]->[extendedProperties]
*/
        internal void DeserializeConstraints(SerializationInfo info, StreamingContext context, int serIndex, bool allConstraints) {
            ArrayList constraintList = (ArrayList) info.GetValue(String.Format(CultureInfo.InvariantCulture, "DataTable_{0}.Constraints", serIndex), typeof(ArrayList));

            foreach (ArrayList list in constraintList) {
                string con = (string) list[0];

                if (con.Equals("U")) { //Unique Constraints
                    string constraintName = (string) list[1];

                    int[] keyColumnIndexes = (int[]) list[2];
                    bool isPrimaryKey = (bool) list[3];
                    PropertyCollection extendedProperties = (PropertyCollection) list[4];

                    DataColumn[] keyColumns = new DataColumn[keyColumnIndexes.Length];
                    for (int i = 0; i < keyColumnIndexes.Length; i++) {
                        keyColumns[i] = Columns[keyColumnIndexes[i]];
                    }

                    //Create the constraint.
                    UniqueConstraint uc = new UniqueConstraint(constraintName, keyColumns, isPrimaryKey);
                    uc.extendedProperties = extendedProperties;

                    //Add the unique constraint and it will in turn set the primary keys also if needed.
                    Constraints.Add(uc);
                } else { //ForeignKeyConstraints
                    Debug.Assert(con.Equals("F"));

                    string constraintName = (string) list[1];
                    int[] parentInfo = (int[]) list[2];
                    int[] childInfo = (int[]) list[3];
                    int[] rules = (int[]) list[4];
                    PropertyCollection extendedProperties = (PropertyCollection) list[5];

                    //ParentKey Columns.
                    DataTable parentTable = (allConstraints == false) ? this : this.DataSet.Tables[parentInfo[0]];
                    DataColumn[] parentkeyColumns = new DataColumn[parentInfo.Length - 1];
                    for (int i = 0; i < parentkeyColumns.Length; i++) {
                        parentkeyColumns[i] = parentTable.Columns[parentInfo[i + 1]];
                    }

                    //ChildKey Columns.
                    DataTable childTable = (allConstraints == false) ? this : this.DataSet.Tables[childInfo[0]];
                    DataColumn[] childkeyColumns = new DataColumn[childInfo.Length - 1];
                    for (int i = 0; i < childkeyColumns.Length; i++) {
                        childkeyColumns[i] = childTable.Columns[childInfo[i + 1]];
                    }

                    //Create the Constraint.
                    ForeignKeyConstraint fk = new ForeignKeyConstraint(constraintName, parentkeyColumns, childkeyColumns);
                    fk.AcceptRejectRule = (AcceptRejectRule) rules[0];
                    fk.UpdateRule = (Rule) rules[1];
                    fk.DeleteRule = (Rule) rules[2];
                    fk.extendedProperties = extendedProperties;

                    //Add just the foreign key constraint without creating unique constraint.
                    Constraints.Add(fk, false);
                }
            }
        }
        /// <summary>
        /// Get Extended Property from Object
        /// </summary>
        /// <param name="obj">Data Object</param>
        /// <param name="propName">Property Name</param>
        /// <returns>Property Value</returns>
        public static string GetExtendedProperty(object obj, string propName)
        {
            if (obj is System.Data.DataSet)
            {
                System.Data.DataSet dataSet = obj as System.Data.DataSet;
                if (dataSet.ExtendedProperties.Contains(propName))
                {
                    return((string)dataSet.ExtendedProperties[propName]);
                }

                return(null);
            }

            if (obj is System.Data.DataTable)
            {
                System.Data.DataTable dataTable = obj as System.Data.DataTable;
                if (dataTable.ExtendedProperties.Contains(propName))
                {
                    return((string)dataTable.ExtendedProperties[propName]);
                }

                return(null);
            }

            if (obj is System.Data.DataColumn)
            {
                System.Data.DataColumn dataColumn = obj as System.Data.DataColumn;
                if (dataColumn.ExtendedProperties.Contains(propName))
                {
                    return((string)dataColumn.ExtendedProperties[propName]);
                }

                return(null);
            }

            if (obj is System.Data.DataRelation)
            {
                System.Data.DataRelation dataRelation = obj as System.Data.DataRelation;
                if (dataRelation.ExtendedProperties.Contains(propName))
                {
                    return((string)dataRelation.ExtendedProperties[propName]);
                }

                return(null);
            }

            if (obj is System.Data.UniqueConstraint)
            {
                System.Data.UniqueConstraint uc = obj as System.Data.UniqueConstraint;
                if (uc.ExtendedProperties.Contains(propName))
                {
                    return((string)uc.ExtendedProperties[propName]);
                }

                return(null);
            }

            if (obj is System.Data.ForeignKeyConstraint)
            {
                System.Data.ForeignKeyConstraint fkc = obj as System.Data.ForeignKeyConstraint;
                if (fkc.ExtendedProperties.Contains(propName))
                {
                    return((string)fkc.ExtendedProperties[propName]);
                }

                return(null);
            }
            return(null);
        }
示例#32
0
            protected override void AddCore(DataRelation relation)
            {
                base.AddCore(relation);
                if (relation.ChildTable.DataSet != _dataSet || relation.ParentTable.DataSet != _dataSet)
                {
                    throw ExceptionBuilder.ForeignRelation();
                }

                relation.CheckState();
                if (relation.Nested)
                {
                    relation.CheckNestedRelations();
                }

                if (relation._relationName.Length == 0)
                {
                    relation._relationName = AssignName();
                }
                else
                {
                    RegisterName(relation._relationName);
                }

                DataKey childKey = relation.ChildKey;

                for (int i = 0; i < _relations.Count; i++)
                {
                    if (childKey.ColumnsEqual(((DataRelation)_relations[i] !).ChildKey))
                    {
                        if (relation.ParentKey.ColumnsEqual(((DataRelation)_relations[i] !).ParentKey))
                        {
                            throw ExceptionBuilder.RelationAlreadyExists();
                        }
                    }
                }

                _relations.Add(relation);
                ((DataTableRelationCollection)(relation.ParentTable.ChildRelations)).Add(relation); // Caching in ParentTable -> ChildRelations
                ((DataTableRelationCollection)(relation.ChildTable.ParentRelations)).Add(relation); // Caching in ChildTable -> ParentRelations

                relation.SetDataSet(_dataSet);
                relation.ChildKey.GetSortIndex().AddRef();
                if (relation.Nested)
                {
                    relation.ChildTable.CacheNestedParent();
                }

                ForeignKeyConstraint?foreignKey = relation.ChildTable.Constraints.FindForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference);

                if (relation._createConstraints)
                {
                    if (foreignKey == null)
                    {
                        relation.ChildTable.Constraints.Add(foreignKey = new ForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference));

                        // try to name the fk constraint the same as the parent relation:
                        try
                        {
                            foreignKey.ConstraintName = relation.RelationName;
                        }
                        catch (Exception e) when(Common.ADP.IsCatchableExceptionType(e))
                        {
                            ExceptionBuilder.TraceExceptionWithoutRethrow(e);
                        }
                    }
                }
                UniqueConstraint?key = relation.ParentTable.Constraints.FindKeyConstraint(relation.ParentColumnsReference);

                relation.SetParentKeyConstraint(key);
                relation.SetChildKeyConstraint(foreignKey);
            }
示例#33
0
            protected override void AddCore(DataRelation relation)
            {
                base.AddCore(relation);
                if (relation.ChildTable.DataSet != dataSet || relation.ParentTable.DataSet != dataSet)
                {
                    throw ExceptionBuilder.ForeignRelation();
                }

                relation.CheckState();
                if (relation.Nested)
                {
                    relation.CheckNestedRelations();
                }

                if (relation.relationName.Length == 0)
                {
                    relation.relationName = AssignName();
                }
                else
                {
                    RegisterName(relation.relationName);
                }

                DataKey childKey = relation.ChildKey;

                for (int i = 0; i < relations.Count; i++)
                {
                    if (childKey.ColumnsEqual(((DataRelation)relations[i]).ChildKey))
                    {
                        if (relation.ParentKey.ColumnsEqual(((DataRelation)relations[i]).ParentKey))
                        {
                            throw ExceptionBuilder.RelationAlreadyExists();
                        }
                    }
                }

                relations.Add(relation);
                ((DataRelationCollection.DataTableRelationCollection)(relation.ParentTable.ChildRelations)).Add(relation); // Caching in ParentTable -> ChildRelations
                ((DataRelationCollection.DataTableRelationCollection)(relation.ChildTable.ParentRelations)).Add(relation); // Caching in ChildTable -> ParentRelations

                relation.SetDataSet(dataSet);
                relation.ChildKey.GetSortIndex().AddRef();
                if (relation.Nested)
                {
                    relation.ChildTable.CacheNestedParent(relation);
                }

                ForeignKeyConstraint foreignKey = relation.ChildTable.Constraints.FindForeignKeyConstraint(relation.ParentColumns, relation.ChildColumns);

                if (relation.createConstraints)
                {
                    if (foreignKey == null)
                    {
                        relation.ChildTable.Constraints.Add(foreignKey = new ForeignKeyConstraint(relation.ParentColumns, relation.ChildColumns));

                        // try to name the fk constraint the same as the parent relation:
                        try {
                            foreignKey.ConstraintName = relation.RelationName;
                        } catch {
                            // ignore the exception
                        }
                    }
                }
                UniqueConstraint key = relation.ParentTable.Constraints.FindKeyConstraint(relation.ParentColumns);

                relation.SetParentKeyConstraint(key);
                relation.SetChildKeyConstraint(foreignKey);
            }
示例#34
0
        internal bool CanRemove(DataTable table, bool fThrowException)
        {
            if (table == null)
            {
                if (!fThrowException)
                {
                    return(false);
                }
                else
                {
                    throw ExceptionBuilder.ArgumentNull("table");
                }
            }
            if (table.DataSet != dataSet)
            {
                if (!fThrowException)
                {
                    return(false);
                }
                else
                {
                    throw ExceptionBuilder.TableNotInTheDataSet(table.TableName);
                }
            }

            // allow subclasses to throw.
            dataSet.OnRemoveTableHack(table);

            if (table.ChildRelations.Count != 0 || table.ParentRelations.Count != 0)
            {
                if (!fThrowException)
                {
                    return(false);
                }
                else
                {
                    throw ExceptionBuilder.TableInRelation();
                }
            }

            for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(dataSet, table); constraints.GetNext();)
            {
                ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint();
                if (!fThrowException)
                {
                    return(false);
                }
                else
                {
                    throw ExceptionBuilder.TableInConstraint(table, constraint);
                }
            }

            for (ChildForeignKeyConstraintEnumerator constraints = new ChildForeignKeyConstraintEnumerator(dataSet, table); constraints.GetNext();)
            {
                ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint();
                if (!fThrowException)
                {
                    return(false);
                }
                else
                {
                    throw ExceptionBuilder.TableInConstraint(table, constraint);
                }
            }

            return(true);
        }
示例#35
0
 internal void SetChildKeyConstraint(ForeignKeyConstraint foreignKeyConstraint)
 {
     childKeyConstraint = foreignKeyConstraint;
 }
示例#36
0
 internal void FinishInitConstraints()
 {
     if (this.delayLoadingConstraints != null)
     {
         for (int i = 0; i < this.delayLoadingConstraints.Length; i++)
         {
             DataColumn[] columnArray;
             int          length;
             if (this.delayLoadingConstraints[i] is UniqueConstraint)
             {
                 if (!this.fLoadForeignKeyConstraintsOnly)
                 {
                     UniqueConstraint constraint2 = (UniqueConstraint)this.delayLoadingConstraints[i];
                     if (constraint2.columnNames == null)
                     {
                         this.Add(constraint2);
                     }
                     else
                     {
                         length      = constraint2.columnNames.Length;
                         columnArray = new DataColumn[length];
                         for (int j = 0; j < length; j++)
                         {
                             columnArray[j] = this.table.Columns[constraint2.columnNames[j]];
                         }
                         if (constraint2.bPrimaryKey)
                         {
                             if (this.table.primaryKey != null)
                             {
                                 throw ExceptionBuilder.AddPrimaryKeyConstraint();
                             }
                             this.Add(constraint2.ConstraintName, columnArray, true);
                         }
                         else
                         {
                             UniqueConstraint constraint4 = new UniqueConstraint(constraint2.constraintName, columnArray);
                             if (this.FindConstraint(constraint4) == null)
                             {
                                 this.Add(constraint4);
                             }
                         }
                     }
                 }
             }
             else
             {
                 ForeignKeyConstraint constraint = (ForeignKeyConstraint)this.delayLoadingConstraints[i];
                 if ((constraint.parentColumnNames == null) || (constraint.childColumnNames == null))
                 {
                     this.Add(constraint);
                 }
                 else if (this.table.DataSet == null)
                 {
                     this.fLoadForeignKeyConstraintsOnly = true;
                 }
                 else
                 {
                     length      = constraint.parentColumnNames.Length;
                     columnArray = new DataColumn[length];
                     DataColumn[] childColumns = new DataColumn[length];
                     for (int k = 0; k < length; k++)
                     {
                         if (constraint.parentTableNamespace == null)
                         {
                             columnArray[k] = this.table.DataSet.Tables[constraint.parentTableName].Columns[constraint.parentColumnNames[k]];
                         }
                         else
                         {
                             columnArray[k] = this.table.DataSet.Tables[constraint.parentTableName, constraint.parentTableNamespace].Columns[constraint.parentColumnNames[k]];
                         }
                         childColumns[k] = this.table.Columns[constraint.childColumnNames[k]];
                     }
                     ForeignKeyConstraint constraint3 = new ForeignKeyConstraint(constraint.constraintName, columnArray, childColumns)
                     {
                         AcceptRejectRule = constraint.acceptRejectRule,
                         DeleteRule       = constraint.deleteRule,
                         UpdateRule       = constraint.updateRule
                     };
                     this.Add(constraint3);
                 }
             }
         }
         if (!this.fLoadForeignKeyConstraintsOnly)
         {
             this.delayLoadingConstraints = null;
         }
     }
 }
            protected override void AddCore(DataRelation relation) {
                base.AddCore(relation);
                if (relation.ChildTable.DataSet != dataSet || relation.ParentTable.DataSet != dataSet)
                    throw ExceptionBuilder.ForeignRelation();

                relation.CheckState();
                if(relation.Nested) {
                    relation.CheckNestedRelations();
                }

                if (relation.relationName.Length == 0)
                    relation.relationName = AssignName();
                else
                    RegisterName(relation.relationName);

                DataKey childKey = relation.ChildKey;

                for (int i = 0; i < relations.Count; i++) {
                    if (childKey.ColumnsEqual(((DataRelation)relations[i]).ChildKey)) {
                        if (relation.ParentKey.ColumnsEqual(((DataRelation)relations[i]).ParentKey))
                            throw ExceptionBuilder.RelationAlreadyExists();
                    }
                }

                relations.Add(relation);
                ((DataRelationCollection.DataTableRelationCollection)(relation.ParentTable.ChildRelations)).Add(relation); // Caching in ParentTable -> ChildRelations
                ((DataRelationCollection.DataTableRelationCollection)(relation.ChildTable.ParentRelations)).Add(relation); // Caching in ChildTable -> ParentRelations

                relation.SetDataSet(dataSet);
                relation.ChildKey.GetSortIndex().AddRef();
                if (relation.Nested) {
                    relation.ChildTable.CacheNestedParent();
                }

                ForeignKeyConstraint foreignKey = relation.ChildTable.Constraints.FindForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference);
                if (relation.createConstraints) {
                    if (foreignKey == null) {
                        relation.ChildTable.Constraints.Add(foreignKey = new ForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference));

                        // try to name the fk constraint the same as the parent relation:
                        try {
                            foreignKey.ConstraintName = relation.RelationName;
                        }
                        catch (Exception e) {
                            // 
                            if (!Common.ADP.IsCatchableExceptionType(e)) {
                                throw;
                            }
                            ExceptionBuilder.TraceExceptionWithoutRethrow(e);
                            // ignore the exception
                        }
                    }
                }
                UniqueConstraint key = relation.ParentTable.Constraints.FindKeyConstraint(relation.ParentColumnsReference);
                relation.SetParentKeyConstraint(key);
                relation.SetChildKeyConstraint(foreignKey);
            }
 internal void SetChildKeyConstraint(ForeignKeyConstraint value)
 {
     this.childKeyConstraint = value;
 }
 private void InitClass()
 {
     DataSetName = "Map_Info_Tables";
     Prefix = "";
     Namespace = "";
     Locale = new CultureInfo("en-US");
     CaseSensitive = false;
     EnforceConstraints = true;
     tableFeature = new FeatureDataTable();
     Tables.Add(tableFeature);
     tableStreet = new StreetDataTable();
     Tables.Add(tableStreet);
     tableCorporation_Link = new Corporation_LinkDataTable();
     Tables.Add(tableCorporation_Link);
     tablePerson_Link = new Person_LinkDataTable();
     Tables.Add(tablePerson_Link);
     tableSheet_Link = new Sheet_LinkDataTable();
     Tables.Add(tableSheet_Link);
     ForeignKeyConstraint fkc;
     fkc = new ForeignKeyConstraint("Feature_Corp_Link", new DataColumn[]
                                                             {
                                                                 tableFeature.FeatureIDColumn
                                                             }, new DataColumn[]
                                                                    {
                                                                        tableCorporation_Link.FeatureIDColumn
                                                                    });
     tableCorporation_Link.Constraints.Add(fkc);
     fkc.AcceptRejectRule = AcceptRejectRule.None;
     fkc.DeleteRule = Rule.Cascade;
     fkc.UpdateRule = Rule.Cascade;
     fkc = new ForeignKeyConstraint("Feature_Person_Link", new DataColumn[]
                                                               {
                                                                   tableFeature.FeatureIDColumn
                                                               }, new DataColumn[]
                                                                      {
                                                                          tablePerson_Link.FeatureIDColumn
                                                                      });
     tablePerson_Link.Constraints.Add(fkc);
     fkc.AcceptRejectRule = AcceptRejectRule.None;
     fkc.DeleteRule = Rule.Cascade;
     fkc.UpdateRule = Rule.Cascade;
     fkc = new ForeignKeyConstraint("Feature_Sheet_Link", new DataColumn[]
                                                              {
                                                                  tableFeature.FeatureIDColumn
                                                              }, new DataColumn[]
                                                                     {
                                                                         tableSheet_Link.FeatureIDColumn
                                                                     });
     tableSheet_Link.Constraints.Add(fkc);
     fkc.AcceptRejectRule = AcceptRejectRule.None;
     fkc.DeleteRule = Rule.Cascade;
     fkc.UpdateRule = Rule.Cascade;
     relationFeature_Corp_Link = new DataRelation("Feature_Corp_Link", new DataColumn[]
                                                                           {
                                                                               tableFeature.FeatureIDColumn
                                                                           }, new DataColumn[]
                                                                                  {
                                                                                      tableCorporation_Link.FeatureIDColumn
                                                                                  }, false);
     Relations.Add(relationFeature_Corp_Link);
     relationFeature_Person_Link = new DataRelation("Feature_Person_Link", new DataColumn[]
                                                                               {
                                                                                   tableFeature.FeatureIDColumn
                                                                               }, new DataColumn[]
                                                                                      {
                                                                                          tablePerson_Link.FeatureIDColumn
                                                                                      }, false);
     Relations.Add(relationFeature_Person_Link);
     relationFeature_Sheet_Link = new DataRelation("Feature_Sheet_Link", new DataColumn[]
                                                                             {
                                                                                 tableFeature.FeatureIDColumn
                                                                             }, new DataColumn[]
                                                                                    {
                                                                                        tableSheet_Link.FeatureIDColumn
                                                                                    }, false);
     Relations.Add(relationFeature_Sheet_Link);
 }
示例#40
0
 internal void SetChildKeyConstraint(ForeignKeyConstraint value)
 {
     Debug.Assert(_childKeyConstraint == null || value == null, "ChildKeyConstraint should not have been set already.");
     _childKeyConstraint = value;
 }
示例#41
0
	public void DataSetSerializationTest2 ()
	{
		DataSet ds = new DataSet ();
		//Table1
		DataTable tb1 = new DataTable ();
		tb1.Columns.Add ("id", typeof (int));
		tb1.Columns.Add ("name", typeof (string));
		tb1.Rows.Add (new object[] {1, "A"});
		tb1.Rows.Add (new object[] {2, "B"});
		ds.Tables.Add (tb1);
		//Table2
		DataTable tb2 = new DataTable ();
		tb2.Columns.Add ("RollNO", typeof (int));
		tb2.Columns.Add ("Name", typeof (string));
		tb2.Rows.Add (new object[] {1, "A"});
		tb2.Rows.Add (new object[] {2, "B"});
		ds.Tables.Add (tb2);
		//Constraints and relations
		ForeignKeyConstraint fKey = new ForeignKeyConstraint (tb2.Columns ["RollNO"], 
								      tb1.Columns ["id"]);
		tb1.Constraints.Add (fKey);
		DataRelation rel = new DataRelation ("Relation1", tb1.Columns ["name"], 
						    tb2.Columns ["Name"]);
		ds.Relations.Add (rel);
		//SerializeDataSet
		BinaryFormatter bf = new BinaryFormatter ();
		ds.RemotingFormat = SerializationFormat.Binary;
		FileStream fs = new FileStream ("Test/System.Data/binserialize/BS-tb4.bin", FileMode.Open, FileAccess.Read);
		BinaryReader r = new BinaryReader (fs);
		byte [] serializedStream = r.ReadBytes ((int) fs.Length);
		r.Close ();
		fs.Close ();
		//DserializeDataSet
		MemoryStream ms = new MemoryStream (serializedStream);
		DataSet ds1 = (DataSet)bf.Deserialize (ms);
		ms.Close ();
		//Test DataSet Properties
		//Assert.AreEqual (ds.RemotingFormat, ds1.RemotingFormat, "#1 RemotingFormat is different");
		Assert.AreEqual (ds.DataSetName, ds1.DataSetName, "#2 DataSetName is different");
		Assert.AreEqual (ds.Namespace, ds1.Namespace, "#3 Namespace is different");
		Assert.AreEqual (ds.Prefix, ds1.Prefix, "#4 Prefix is different");
		Assert.AreEqual (ds.CaseSensitive, ds1.CaseSensitive, "#5 CaseSensitive property value is different");
		Assert.AreEqual (ds.Locale.LCID, ds1.Locale.LCID, "#6 DataSet LocaleLCID is different");
		Assert.AreEqual (ds.EnforceConstraints, ds1.EnforceConstraints, "#7 EnforceConstraints property value is different");
		Assert.AreEqual (ds.Tables.Count, ds1.Tables.Count, "#7 Table Count is different");

		//Test Constraints & relations

		//Table1
		Assert.AreEqual (ds.Tables [0].Constraints.Count, ds1.Tables [0].Constraints.Count, "#8 Number of constraint is different for Table :{0}", ds.Tables [0].TableName);

		for (int i = 0; i < ds.Tables [0].Constraints.Count; i++)
			Assert.AreEqual (ds.Tables [0].Constraints [i].GetType (), 
					 ds1.Tables [0].Constraints [i].GetType (), 
					 "#9 Constraint : {0} is Different", ds.Tables [0].Constraints [i]);

		//Table2 
		Assert.AreEqual (ds.Tables [1].Constraints.Count, ds1.Tables [1].Constraints.Count, "#10 Number of constraint is different for Table :{0}", ds.Tables [1].TableName);

		for (int i = 0; i < ds.Tables [1].Constraints.Count; i++)
			Assert.AreEqual (ds.Tables [1].Constraints [i].GetType (), 
					 ds1.Tables [1].Constraints [i].GetType (), 
					 "#11 Constraint : {0} is Different", ds.Tables [1].Constraints [i]);
		//Relations
		Assert.AreEqual (ds.Relations.Count, ds1.Relations.Count, "#12 Relation count is different");
		for (int i = 0; i < ds.Relations.Count; i++)
			Assert.AreEqual (ds.Relations [i].RelationName, ds1.Relations [i].RelationName, "#13 Relation Name is different for relation :{0}", ds.Relations [i].RelationName);

		for (int i = 0; i < ds.Relations.Count; i++)
			Assert.AreEqual (ds.Relations [i].ParentTable.TableName, 
					 ds1.Relations[i].ParentTable.TableName, "#14 Relation Name is different for relation :{0}", ds.Relations [i].ParentTable.TableName);	
		
		for (int i = 0; i < ds.Relations.Count; i++)
			Assert.AreEqual (ds.Relations [i].ChildTable.TableName, 
					 ds1.Relations[i].ChildTable.TableName, "#15 Relation Name is different for relation :{0}", ds.Relations [i].ChildTable.TableName);	
		
		//Table Data
		//Table1
		for (int i = 0; i < ds.Tables [0].Rows.Count; i++) 
			for (int j = 0; j < ds.Tables [0].Columns.Count; j++) {
				Assert.AreEqual (ds.Tables [0].Rows [i][j], ds1.Tables [0].Rows [i][j], 
						 "#16 Elements differ at Row :{0} Column :{1}", i, j);
			}
		//Table2
		for (int i = 0; i < ds.Tables [0].Rows.Count; i++) 
			for (int j = 0; j < ds.Tables [1].Columns.Count; j++) {
				Assert.AreEqual (ds.Tables [1].Rows [i][j], ds1.Tables [1].Rows [i][j], 
						 "#17 Elements differ at Row :{0} Column :{1}", i, j);
			}
		
	}
示例#42
0
        internal override Constraint Clone(DataSet destination, bool ignorNSforTableLookup)
        {
            int iDest;

            if (ignorNSforTableLookup)
            {
                iDest = destination.Tables.IndexOf(Table.TableName);
            }
            else
            {
                iDest = destination.Tables.IndexOf(Table.TableName, Table.Namespace, false); // pass false for last param
                // to be backward compatable, otherwise meay cause new exception
            }

            if (iDest < 0)
            {
                return(null);
            }

            DataTable table = destination.Tables[iDest];

            if (ignorNSforTableLookup)
            {
                iDest = destination.Tables.IndexOf(RelatedTable.TableName);
            }
            else
            {
                iDest = destination.Tables.IndexOf(RelatedTable.TableName, RelatedTable.Namespace, false); // pass false for last param
            }
            if (iDest < 0)
            {
                return(null);
            }

            DataTable relatedTable = destination.Tables[iDest];

            int keys = Columns.Length;

            DataColumn[] columns        = new DataColumn[keys];
            DataColumn[] relatedColumns = new DataColumn[keys];

            for (int i = 0; i < keys; i++)
            {
                DataColumn src = Columns[i];
                iDest = table.Columns.IndexOf(src.ColumnName);
                if (iDest < 0)
                {
                    return(null);
                }
                columns[i] = table.Columns[iDest];

                src   = RelatedColumnsReference[i];
                iDest = relatedTable.Columns.IndexOf(src.ColumnName);
                if (iDest < 0)
                {
                    return(null);
                }
                relatedColumns[i] = relatedTable.Columns[iDest];
            }
            ForeignKeyConstraint clone = new ForeignKeyConstraint(ConstraintName, relatedColumns, columns);

            clone.UpdateRule       = UpdateRule;
            clone.DeleteRule       = DeleteRule;
            clone.AcceptRejectRule = AcceptRejectRule;

            // ...Extended Properties
            foreach (object key in ExtendedProperties.Keys)
            {
                clone.ExtendedProperties[key] = ExtendedProperties[key];
            }

            return(clone);
        }
示例#43
0
        internal override Constraint Clone(DataSet destination, bool ignorNSforTableLookup) {
            int iDest;
            if (ignorNSforTableLookup) {
                iDest = destination.Tables.IndexOf(Table.TableName);
            }
            else {
                iDest = destination.Tables.IndexOf(Table.TableName, Table.Namespace, false); // pass false for last param 
                // to be backward compatable, otherwise meay cause new exception
            }
            
            if (iDest < 0)
                return null;
            DataTable table = destination.Tables[iDest];
            if (ignorNSforTableLookup) {
                iDest = destination.Tables.IndexOf(RelatedTable.TableName);
            }
            else {
                iDest = destination.Tables.IndexOf(RelatedTable.TableName, RelatedTable.Namespace, false);// pass false for last param 
            }            
            if (iDest < 0)
                return null;
            DataTable relatedTable = destination.Tables[iDest];

            int keys = Columns.Length;
            DataColumn[] columns = new DataColumn[keys];
            DataColumn[] relatedColumns = new DataColumn[keys];

            for (int i = 0; i < keys; i++) {
                DataColumn src = Columns[i];
                iDest = table.Columns.IndexOf(src.ColumnName);
                if (iDest < 0)
                    return null;
                columns[i] = table.Columns[iDest];

                src = RelatedColumnsReference[i];
                iDest = relatedTable.Columns.IndexOf(src.ColumnName);
                if (iDest < 0)
                    return null;
                relatedColumns[i] = relatedTable.Columns[iDest];
            }
            ForeignKeyConstraint clone = new ForeignKeyConstraint(ConstraintName,relatedColumns, columns);
            clone.UpdateRule = this.UpdateRule;
            clone.DeleteRule = this.DeleteRule;
            clone.AcceptRejectRule = this.AcceptRejectRule;

            // ...Extended Properties
            foreach(Object key in this.ExtendedProperties.Keys) {
                clone.ExtendedProperties[key]=this.ExtendedProperties[key];
            }

            return clone;
        }
        private static bool AdjustSchemaRelations(DataSet targetSet, DataSet sourceSet, MissingSchemaAction missingSchemaAction)
        {
            if (missingSchemaAction == MissingSchemaAction.Ignore)
            {
                return(true);
            }

            foreach (DataTable sourceTable in sourceSet.Tables)
            {
                DataTable targetTable = targetSet.Tables[sourceTable.TableName];
                if (targetTable == null)
                {
                    continue;
                }

                foreach (Constraint constraint in sourceTable.Constraints)
                {
                    Constraint targetConstraint = null;

                    string constraintName = constraint.ConstraintName;
                    if (targetTable.Constraints.Contains(constraintName))
                    {
                        constraintName = "";
                    }

                    UniqueConstraint uc = constraint as UniqueConstraint;
                    // PrimaryKey is already taken care of while merging the table
                    // ForeignKey constraint takes care of Parent Unique Constraints
                    if (uc != null)
                    {
                        if (uc.IsPrimaryKey || uc.ChildConstraint != null)
                        {
                            continue;
                        }
                        DataColumn[] columns = ResolveColumns(targetTable, uc.Columns);
                        targetConstraint = new UniqueConstraint(constraintName, columns, false);
                    }

                    ForeignKeyConstraint fc = constraint as ForeignKeyConstraint;
                    if (fc != null)
                    {
                        DataColumn[] columns        = ResolveColumns(targetTable, fc.Columns);
                        DataColumn[] relatedColumns = ResolveColumns(targetSet.Tables [fc.RelatedTable.TableName],
                                                                     fc.RelatedColumns);
                        targetConstraint = new ForeignKeyConstraint(constraintName, relatedColumns, columns);
                    }

                    bool dupConstraintFound = false;
                    foreach (Constraint cons in targetTable.Constraints)
                    {
                        if (!targetConstraint.Equals(cons))
                        {
                            continue;
                        }
                        dupConstraintFound = true;
                        break;
                    }

                    // If equivalent-constraint already exists, then just do nothing
                    if (dupConstraintFound)
                    {
                        continue;
                    }

                    if (missingSchemaAction == MissingSchemaAction.Error)
                    {
                        throw new DataException("Target DataSet missing " + targetConstraint.GetType() +
                                                targetConstraint.ConstraintName);
                    }
                    else
                    {
                        targetTable.Constraints.Add(targetConstraint);
                    }
                }
            }

            foreach (DataRelation relation in sourceSet.Relations)
            {
                DataRelation targetRelation = targetSet.Relations [relation.RelationName];
                if (targetRelation == null)
                {
                    if (missingSchemaAction == MissingSchemaAction.Error)
                    {
                        throw new ArgumentException("Target DataSet mising definition for " +
                                                    relation.RelationName);
                    }

                    DataColumn[] parentColumns = ResolveColumns(targetSet.Tables [relation.ParentTable.TableName],
                                                                relation.ParentColumns);
                    DataColumn[] childColumns = ResolveColumns(targetSet.Tables [relation.ChildTable.TableName],
                                                               relation.ChildColumns);
                    targetRelation = targetSet.Relations.Add(relation.RelationName, parentColumns,
                                                             childColumns, relation.createConstraints);
                    targetRelation.Nested = relation.Nested;
                }
                else if (!CompareColumnArrays(relation.ParentColumns, targetRelation.ParentColumns) ||
                         !CompareColumnArrays(relation.ChildColumns, targetRelation.ChildColumns))
                {
                    RaiseMergeFailedEvent(null, "Relation " + relation.RelationName +
                                          " cannot be merged, because keys have mismatch columns.");
                }
            }

            return(true);
        }
示例#45
0
    private static DataTableForeignKeyDescription GetDataGridForeignKeyDescriptionForForeignKeyConstraint(
      ForeignKeyConstraint foreignKeyConstraint )
    {
      DataTableForeignKeyDescription foreignKeyDescription = null;

      if( foreignKeyConstraint != null )
      {
        if( ( foreignKeyConstraint.Columns != null )
          && ( foreignKeyConstraint.Columns.Length == 1 ) )
        {
          foreignKeyDescription = new DataTableForeignKeyDescription();
          ( ( DataTableForeignKeyDescription )foreignKeyDescription ).ForeignKeyConstraint = foreignKeyConstraint;
          foreignKeyDescription.IsAutoCreated = true;
        }
      }

      return foreignKeyDescription;
    }
示例#46
0
 public static Exception RemoveParentRow(ForeignKeyConstraint constraint) => _InvalidConstraint(SR.Format(SR.DataConstraint_RemoveParentRow, constraint.ConstraintName));
示例#47
0
		Constraint Add (string name, DataColumn[] primaryKeyColumns, DataColumn[] foreignKeyColumns)
		{
			ForeignKeyConstraint fc = new ForeignKeyConstraint (name, primaryKeyColumns, foreignKeyColumns);
			Add (fc);
			return fc;
		}
示例#48
0
        internal bool CanRemove(DataTable table, bool fThrowException)
        {
            bool   flag;
            IntPtr ptr;

            Bid.ScopeEnter(out ptr, "<ds.DataTableCollection.CanRemove|INFO> %d#, table=%d, fThrowException=%d{bool}\n", this.ObjectID, (table != null) ? table.ObjectID : 0, fThrowException);
            try
            {
                if (table == null)
                {
                    if (fThrowException)
                    {
                        throw ExceptionBuilder.ArgumentNull("table");
                    }
                    return(false);
                }
                if (table.DataSet != this.dataSet)
                {
                    if (fThrowException)
                    {
                        throw ExceptionBuilder.TableNotInTheDataSet(table.TableName);
                    }
                    return(false);
                }
                this.dataSet.OnRemoveTable(table);
                if ((table.ChildRelations.Count != 0) || (table.ParentRelations.Count != 0))
                {
                    if (fThrowException)
                    {
                        throw ExceptionBuilder.TableInRelation();
                    }
                    return(false);
                }
                ParentForeignKeyConstraintEnumerator enumerator2 = new ParentForeignKeyConstraintEnumerator(this.dataSet, table);
                while (enumerator2.GetNext())
                {
                    ForeignKeyConstraint foreignKeyConstraint = enumerator2.GetForeignKeyConstraint();
                    if ((foreignKeyConstraint.Table != table) || (foreignKeyConstraint.RelatedTable != table))
                    {
                        if (fThrowException)
                        {
                            throw ExceptionBuilder.TableInConstraint(table, foreignKeyConstraint);
                        }
                        return(false);
                    }
                }
                ChildForeignKeyConstraintEnumerator enumerator = new ChildForeignKeyConstraintEnumerator(this.dataSet, table);
                while (enumerator.GetNext())
                {
                    ForeignKeyConstraint constraint = enumerator.GetForeignKeyConstraint();
                    if ((constraint.Table != table) || (constraint.RelatedTable != table))
                    {
                        if (fThrowException)
                        {
                            throw ExceptionBuilder.TableInConstraint(table, constraint);
                        }
                        return(false);
                    }
                }
                flag = true;
            }
            finally
            {
                Bid.ScopeLeave(ref ptr);
            }
            return(flag);
        }
示例#49
0
		public void AddFkException1 ()
		{
			DataSet ds = new DataSet ();
			ds.Tables.Add (_table);
			_table2.TableName = "TestTable2";
			ds.Tables.Add (_table2);

			_table.Rows.Add (new object [] {1});
			_table.Rows.Add (new object [] {1});

			//FKC: can't create unique constraint because duplicate values already exist
			try {
				ForeignKeyConstraint fkc = new ForeignKeyConstraint (_table.Columns [0],
											_table2.Columns [0]);
				
				_table2.Constraints.Add (fkc);	//should throw			
				Assert.Fail ("B1: Failed to throw ArgumentException.");
			} catch (ArgumentException) {
			} catch (AssertionException exc) {
				throw exc;
			} catch (Exception exc) {
				Assert.Fail ("A1: Wrong Exception type. " + exc.ToString ());
			}
		}
        internal bool CanRemove(DataTable table, bool fThrowException)
        {
            IntPtr hscp;

            Bid.ScopeEnter(out hscp, "<ds.DataTableCollection.CanRemove|INFO> %d#, table=%d, fThrowException=%d{bool}\n", ObjectID, (table != null)? table.ObjectID : 0, fThrowException);
            try {
                if (table == null)
                {
                    if (!fThrowException)
                    {
                        return(false);
                    }
                    else
                    {
                        throw ExceptionBuilder.ArgumentNull("table");
                    }
                }
                if (table.DataSet != dataSet)
                {
                    if (!fThrowException)
                    {
                        return(false);
                    }
                    else
                    {
                        throw ExceptionBuilder.TableNotInTheDataSet(table.TableName);
                    }
                }

                // allow subclasses to throw.
                dataSet.OnRemoveTable(table);

                if (table.ChildRelations.Count != 0 || table.ParentRelations.Count != 0)
                {
                    if (!fThrowException)
                    {
                        return(false);
                    }
                    else
                    {
                        throw ExceptionBuilder.TableInRelation();
                    }
                }

                for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(dataSet, table); constraints.GetNext();)
                {
                    ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint();
                    if (constraint.Table == table && constraint.RelatedTable == table) // we can go with (constraint.Table ==  constraint.RelatedTable)
                    {
                        continue;
                    }
                    if (!fThrowException)
                    {
                        return(false);
                    }
                    else
                    {
                        throw ExceptionBuilder.TableInConstraint(table, constraint);
                    }
                }

                for (ChildForeignKeyConstraintEnumerator constraints = new ChildForeignKeyConstraintEnumerator(dataSet, table); constraints.GetNext();)
                {
                    ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint();
                    if (constraint.Table == table && constraint.RelatedTable == table) // bug 97670
                    {
                        continue;
                    }

                    if (!fThrowException)
                    {
                        return(false);
                    }
                    else
                    {
                        throw ExceptionBuilder.TableInConstraint(table, constraint);
                    }
                }

                return(true);
            }
            finally{
                Bid.ScopeLeave(ref hscp);
            }
        }
示例#51
0
		public void AddRange ()
		{
			_constraint1.ConstraintName = "UK1";
			_constraint2.ConstraintName = "UK12";
                                                                                                    
			ForeignKeyConstraint _constraint3 = new ForeignKeyConstraint ("FK2", _table.Columns [0],
                                        _table2.Columns [0]);
			UniqueConstraint _constraint4 = new UniqueConstraint ("UK2", _table2.Columns [1]);
                                                                                                    
			// Add the constraints.
			Constraint [] constraints = {_constraint1, _constraint2};
			_table.Constraints.AddRange (constraints);
                                                                                                                                                                                                         
			Constraint [] constraints1 = {_constraint3, _constraint4};
			_table2.Constraints.AddRange (constraints1);
                                                                                                    
			Assert.AreEqual ("UK1", _table.Constraints [0].ConstraintName, "A1");
			Assert.AreEqual ("UK12", _table.Constraints [1].ConstraintName, "A2");
                                                                                              
			Assert.AreEqual ("FK2", _table2.Constraints [0].ConstraintName, "A3");
			Assert.AreEqual ("UK2", _table2.Constraints [1].ConstraintName, "A4");
		}
示例#52
0
		public SchemaBuilder WithConstraint(ForeignKeyConstraint action)
		{
			_currentColumn.Constraint = action;

			return this;
		}
		// adjust the dataset schema according to the missingschemaaction param
		// (relations).
		// return false if adjusting fails.
		private static bool AdjustSchema(DataSet targetSet, DataSet sourceSet, MissingSchemaAction missingSchemaAction)
		{
			if (missingSchemaAction == MissingSchemaAction.Add || missingSchemaAction == MissingSchemaAction.AddWithKey) {
				foreach (DataRelation relation in sourceSet.Relations) {
					// TODO : add more precise condition (columns)
					if (!targetSet.Relations.Contains(relation.RelationName)) {
						DataTable targetTable = targetSet.Tables[relation.ParentColumns[0].Table.TableName];
						DataColumn[] parentColumns = ResolveColumns(sourceSet,targetTable,relation.ParentColumns);
						targetTable = targetSet.Tables[relation.ChildColumns[0].Table.TableName];
						DataColumn[] childColumns = ResolveColumns(sourceSet,targetTable,relation.ChildColumns);
						if (parentColumns != null && childColumns != null) {
							DataRelation newRelation = new DataRelation(relation.RelationName,parentColumns,childColumns);
							newRelation.Nested = relation.Nested; 
							targetSet.Relations.Add(newRelation);
						}
					}
					else {
						// TODO : should we throw an exeption ?
					}
				}			

				foreach(DataTable sourceTable in sourceSet.Tables) {				
					DataTable targetTable = targetSet.Tables[sourceTable.TableName];

					if (targetTable != null) {
						foreach(Constraint constraint in sourceTable.Constraints) {

							if (constraint is UniqueConstraint) {
								UniqueConstraint uc = (UniqueConstraint)constraint;
								// FIXME : add more precise condition (columns)
								if ( !targetTable.Constraints.Contains(uc.ConstraintName) ) {		
									DataColumn[] columns = ResolveColumns(sourceSet,targetTable,uc.Columns);
									if (columns != null) {
										UniqueConstraint newConstraint = new UniqueConstraint(uc.ConstraintName,columns,uc.IsPrimaryKey);
										targetTable.Constraints.Add(newConstraint);
									}
								}
								else {
									// FIXME : should we throw an exception ?
								}
							}
							else {
								ForeignKeyConstraint fc = (ForeignKeyConstraint)constraint;
								// FIXME : add more precise condition (columns)
								if (!targetTable.Constraints.Contains(fc.ConstraintName)) {
									DataColumn[] columns = ResolveColumns(sourceSet,targetTable,fc.Columns);
									DataTable relatedTable = targetSet.Tables[fc.RelatedTable.TableName];
									DataColumn[] relatedColumns = ResolveColumns(sourceSet,relatedTable,fc.RelatedColumns);
									if (columns != null && relatedColumns != null) {
										ForeignKeyConstraint newConstraint = new ForeignKeyConstraint(fc.ConstraintName,relatedColumns,columns);
										targetTable.Constraints.Add(newConstraint);
									}
								}
								else {
									// FIXME : should we throw an exception ?
								}
							}
						}
					}
				}
			}

			return true;
		}
示例#54
0
        // To add foreign key constraint without adding any unique constraint for internal use. Main purpose : Binary Remoting
        internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign)
        {
            if (constraint == null)
            {
                throw ExceptionBuilder.ArgumentNull(nameof(constraint));
            }

            // It is an error if we find an equivalent constraint already in collection
            if (FindConstraint(constraint) != null)
            {
                throw ExceptionBuilder.DuplicateConstraint(FindConstraint(constraint).ConstraintName);
            }

            if (1 < _table.NestedParentRelations.Length)
            {
                if (!AutoGenerated(constraint))
                {
                    throw ExceptionBuilder.CantAddConstraintToMultipleNestedTable(_table.TableName);
                }
            }

            if (constraint is UniqueConstraint)
            {
                if (((UniqueConstraint)constraint)._bPrimaryKey)
                {
                    if (Table._primaryKey != null)
                    {
                        throw ExceptionBuilder.AddPrimaryKeyConstraint();
                    }
                }
                AddUniqueConstraint((UniqueConstraint)constraint);
            }
            else if (constraint is ForeignKeyConstraint)
            {
                ForeignKeyConstraint fk = (ForeignKeyConstraint)constraint;
                if (addUniqueWhenAddingForeign)
                {
                    UniqueConstraint key = fk.RelatedTable.Constraints.FindKeyConstraint(fk.RelatedColumnsReference);
                    if (key == null)
                    {
                        if (constraint.ConstraintName.Length == 0)
                        {
                            constraint.ConstraintName = AssignName();
                        }
                        else
                        {
                            RegisterName(constraint.ConstraintName);
                        }

                        key = new UniqueConstraint(fk.RelatedColumnsReference);
                        fk.RelatedTable.Constraints.Add(key);
                    }
                }
                AddForeignKeyConstraint((ForeignKeyConstraint)constraint);
            }
            BaseAdd(constraint);
            ArrayAdd(constraint);
            OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, constraint));

            if (constraint is UniqueConstraint)
            {
                if (((UniqueConstraint)constraint)._bPrimaryKey)
                {
                    Table.PrimaryKey = ((UniqueConstraint)constraint).ColumnsReference;
                }
            }
        }
示例#55
0
        internal bool CanRemove(DataTable table, bool fThrowException)
        {
            long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTableCollection.CanRemove|INFO> {0}, table={1}, fThrowException={2}", ObjectID, (table != null) ? table.ObjectID : 0, fThrowException);

            try
            {
                if (table == null)
                {
                    if (!fThrowException)
                    {
                        return(false);
                    }
                    throw ExceptionBuilder.ArgumentNull(nameof(table));
                }
                if (table.DataSet != _dataSet)
                {
                    if (!fThrowException)
                    {
                        return(false);
                    }
                    throw ExceptionBuilder.TableNotInTheDataSet(table.TableName);
                }

                // allow subclasses to throw.
                _dataSet.OnRemoveTable(table);

                if (table.ChildRelations.Count != 0 || table.ParentRelations.Count != 0)
                {
                    if (!fThrowException)
                    {
                        return(false);
                    }
                    throw ExceptionBuilder.TableInRelation();
                }

                for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(_dataSet, table); constraints.GetNext();)
                {
                    ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint();
                    if (constraint.Table == table && constraint.RelatedTable == table) // we can go with (constraint.Table ==  constraint.RelatedTable)
                    {
                        continue;
                    }
                    if (!fThrowException)
                    {
                        return(false);
                    }
                    else
                    {
                        throw ExceptionBuilder.TableInConstraint(table, constraint);
                    }
                }

                for (ChildForeignKeyConstraintEnumerator constraints = new ChildForeignKeyConstraintEnumerator(_dataSet, table); constraints.GetNext();)
                {
                    ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint();
                    if (constraint.Table == table && constraint.RelatedTable == table)
                    {
                        continue;
                    }

                    if (!fThrowException)
                    {
                        return(false);
                    }
                    else
                    {
                        throw ExceptionBuilder.TableInConstraint(table, constraint);
                    }
                }

                return(true);
            }
            finally
            {
                DataCommonEventSource.Log.ExitScope(logScopeId);
            }
        }
示例#56
0
        internal void FinishInitConstraints()
        {
            if (_delayLoadingConstraints == null)
            {
                return;
            }

            int colCount;

            DataColumn[] parents, childs;
            for (int i = 0; i < _delayLoadingConstraints.Length; i++)
            {
                if (_delayLoadingConstraints[i] is UniqueConstraint)
                {
                    if (_fLoadForeignKeyConstraintsOnly)
                    {
                        continue;
                    }

                    UniqueConstraint constr = (UniqueConstraint)_delayLoadingConstraints[i];
                    if (constr._columnNames == null)
                    {
                        Add(constr);
                        continue;
                    }
                    colCount = constr._columnNames.Length;
                    parents  = new DataColumn[colCount];
                    for (int j = 0; j < colCount; j++)
                    {
                        parents[j] = _table.Columns[constr._columnNames[j]];
                    }
                    if (constr._bPrimaryKey)
                    {
                        if (_table._primaryKey != null)
                        {
                            throw ExceptionBuilder.AddPrimaryKeyConstraint();
                        }
                        else
                        {
                            Add(constr.ConstraintName, parents, true);
                        }
                        continue;
                    }
                    UniqueConstraint newConstraint = new UniqueConstraint(constr._constraintName, parents);
                    if (FindConstraint(newConstraint) == null)
                    {
                        Add(newConstraint);
                    }
                }
                else
                {
                    ForeignKeyConstraint constr = (ForeignKeyConstraint)_delayLoadingConstraints[i];
                    if (constr._parentColumnNames == null || constr._childColumnNames == null)
                    {
                        Add(constr);
                        continue;
                    }

                    if (_table.DataSet == null)
                    {
                        _fLoadForeignKeyConstraintsOnly = true;
                        continue;
                    }

                    colCount = constr._parentColumnNames.Length;
                    parents  = new DataColumn[colCount];
                    childs   = new DataColumn[colCount];
                    for (int j = 0; j < colCount; j++)
                    {
                        if (constr._parentTableNamespace == null)
                        {
                            parents[j] = _table.DataSet.Tables[constr._parentTableName].Columns[constr._parentColumnNames[j]];
                        }
                        else
                        {
                            parents[j] = _table.DataSet.Tables[constr._parentTableName, constr._parentTableNamespace].Columns[constr._parentColumnNames[j]];
                        }
                        childs[j] = _table.Columns[constr._childColumnNames[j]];
                    }
                    ForeignKeyConstraint newConstraint = new ForeignKeyConstraint(constr._constraintName, parents, childs);
                    newConstraint.AcceptRejectRule = constr._acceptRejectRule;
                    newConstraint.DeleteRule       = constr._deleteRule;
                    newConstraint.UpdateRule       = constr._updateRule;
                    Add(newConstraint);
                }
            }

            if (!_fLoadForeignKeyConstraintsOnly)
            {
                _delayLoadingConstraints = null;
            }
        }
示例#57
0
 public static Exception NeededForForeignKeyConstraint(UniqueConstraint key, ForeignKeyConstraint fk) => _Argument(SR.Format(SR.DataConstraint_NeededForForeignKeyConstraint, key.ConstraintName, fk.ConstraintName));
            protected override void AddCore(DataRelation relation)
            {
                base.AddCore(relation);
                if ((relation.ChildTable.DataSet != this.dataSet) || (relation.ParentTable.DataSet != this.dataSet))
                {
                    throw ExceptionBuilder.ForeignRelation();
                }
                relation.CheckState();
                if (relation.Nested)
                {
                    relation.CheckNestedRelations();
                }
                if (relation.relationName.Length == 0)
                {
                    relation.relationName = base.AssignName();
                }
                else
                {
                    base.RegisterName(relation.relationName);
                }
                DataKey childKey = relation.ChildKey;

                for (int i = 0; i < this.relations.Count; i++)
                {
                    if (childKey.ColumnsEqual(((DataRelation)this.relations[i]).ChildKey) && relation.ParentKey.ColumnsEqual(((DataRelation)this.relations[i]).ParentKey))
                    {
                        throw ExceptionBuilder.RelationAlreadyExists();
                    }
                }
                this.relations.Add(relation);
                ((DataRelationCollection.DataTableRelationCollection)relation.ParentTable.ChildRelations).Add(relation);
                ((DataRelationCollection.DataTableRelationCollection)relation.ChildTable.ParentRelations).Add(relation);
                relation.SetDataSet(this.dataSet);
                relation.ChildKey.GetSortIndex().AddRef();
                if (relation.Nested)
                {
                    relation.ChildTable.CacheNestedParent();
                }
                ForeignKeyConstraint constraint = relation.ChildTable.Constraints.FindForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference);

                if (relation.createConstraints && (constraint == null))
                {
                    relation.ChildTable.Constraints.Add(constraint = new ForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference));
                    try
                    {
                        constraint.ConstraintName = relation.RelationName;
                    }
                    catch (Exception exception)
                    {
                        if (!ADP.IsCatchableExceptionType(exception))
                        {
                            throw;
                        }
                        ExceptionBuilder.TraceExceptionWithoutRethrow(exception);
                    }
                }
                UniqueConstraint constraint2 = relation.ParentTable.Constraints.FindKeyConstraint(relation.ParentColumnsReference);

                relation.SetParentKeyConstraint(constraint2);
                relation.SetChildKeyConstraint(constraint);
            }
示例#59
0
			private void InitClass() 
			{
				this.DataSetName = "myTypedDataSet";
				this.Prefix = "";
				this.Namespace = "http://www.tempuri.org/myTypedDataSet.xsd";
				this.Locale = new CultureInfo("en-US");
				this.CaseSensitive = false;
				this.EnforceConstraints = true;
				this.tableOrder_Details = new Order_DetailsDataTable();
				this.Tables.Add(this.tableOrder_Details);
				this.tableOrders = new OrdersDataTable();
				this.Tables.Add(this.tableOrders);
				ForeignKeyConstraint fkc;
				fkc = new ForeignKeyConstraint("OrdersOrder_x0020_Details", new DataColumn[] {
																								 this.tableOrders.OrderIDColumn}, new DataColumn[] {
																																					   this.tableOrder_Details.OrderIDColumn});
				this.tableOrder_Details.Constraints.Add(fkc);
				fkc.AcceptRejectRule = AcceptRejectRule.None;
				fkc.DeleteRule = Rule.Cascade;
				fkc.UpdateRule = Rule.Cascade;
				this.relationOrdersOrder_x0020_Details = new DataRelation("OrdersOrder_x0020_Details", new DataColumn[] {
																															this.tableOrders.OrderIDColumn}, new DataColumn[] {
																																												  this.tableOrder_Details.OrderIDColumn}, false);
				this.Relations.Add(this.relationOrdersOrder_x0020_Details);
			}
示例#60
0
        internal override Constraint Clone(DataSet destination, bool ignorNSforTableLookup)
        {
            int index;

            if (ignorNSforTableLookup)
            {
                index = destination.Tables.IndexOf(this.Table.TableName);
            }
            else
            {
                index = destination.Tables.IndexOf(this.Table.TableName, this.Table.Namespace, false);
            }
            if (index < 0)
            {
                return(null);
            }
            DataTable table2 = destination.Tables[index];

            if (ignorNSforTableLookup)
            {
                index = destination.Tables.IndexOf(this.RelatedTable.TableName);
            }
            else
            {
                index = destination.Tables.IndexOf(this.RelatedTable.TableName, this.RelatedTable.Namespace, false);
            }
            if (index < 0)
            {
                return(null);
            }
            DataTable table  = destination.Tables[index];
            int       length = this.Columns.Length;

            DataColumn[] childColumns  = new DataColumn[length];
            DataColumn[] parentColumns = new DataColumn[length];
            for (int i = 0; i < length; i++)
            {
                DataColumn column = this.Columns[i];
                index = table2.Columns.IndexOf(column.ColumnName);
                if (index < 0)
                {
                    return(null);
                }
                childColumns[i] = table2.Columns[index];
                column          = this.RelatedColumnsReference[i];
                index           = table.Columns.IndexOf(column.ColumnName);
                if (index < 0)
                {
                    return(null);
                }
                parentColumns[i] = table.Columns[index];
            }
            ForeignKeyConstraint constraint = new ForeignKeyConstraint(this.ConstraintName, parentColumns, childColumns)
            {
                UpdateRule       = this.UpdateRule,
                DeleteRule       = this.DeleteRule,
                AcceptRejectRule = this.AcceptRejectRule
            };

            foreach (object obj2 in base.ExtendedProperties.Keys)
            {
                constraint.ExtendedProperties[obj2] = base.ExtendedProperties[obj2];
            }
            return(constraint);
        }