[Mono-dev] Problem with composite System.Data.ForeignKeyConstraint referencing the same DataTable

Sorin Peste neaorin at gmail.com
Mon Oct 16 08:20:13 EDT 2006


Hi everyone,

I ran across this problem while trying to make an older .NET application of
mine Mono-compliant. In a nutshell, I have this DataTable:

Menu
----------------------
+ID
+Culture 
Name
ParentID

(+) signifies a primary key column. 

I also have a foreign key (composite) pointing to the same table : (ID,
Culture) <- (ParentID, Culture). Mono throws an exception when adding the
foreign key to the DataTable:

Unhandled Exception: System.InvalidOperationException: Parent and child
columns
can't be the same column.

This would have been correct if I had tried to add a simple FK like (Culture
<- Culture), but IMO for a composite key there should be no error. The code
should check whether _all_ columns involved are identical, and then throw
the exception.
Now, I know this is a pretty ugly way to model such a situation, but the
point is MS .NET allows this (and at least SQL Server accepts such a data
model). 
Below is a small app to illustrate this problem. It can be made into a unit
test rather easily, and I will do it if this belongs in Bugzilla.



using System.Data;

namespace TestSelfReference
{
	class Class1
	{

		static void Main(string[] args)
		{
			// create a table and some columns
			DataTable dataTable = new DataTable("Menu");
			DataColumn colID = dataTable.Columns.Add("ID",
typeof(int));
			DataColumn colCulture =
dataTable.Columns.Add("Culture", typeof(string));
			DataColumn colName = dataTable.Columns.Add("Name",
typeof(string));
			DataColumn colParentID =
dataTable.Columns.Add("ParentID", typeof(int));

			// table PK (ID, Culture)
			dataTable.Constraints.Add(new UniqueConstraint(
				"MenuPK", 
				new DataColumn[] {colID, colCulture}, 
				true));

			// add a FK referencing the same table: (ID,
Culture) <- (ParentID, Culture)
			ForeignKeyConstraint fkc = new ForeignKeyConstraint(
				"MenuParentFK", 
				new DataColumn[] {colID, colCulture}, 
				new DataColumn[] {colParentID, colCulture});

			dataTable.Constraints.Add(fkc); // !! Mono throws
InvalidOperationException

		}
	}
}


Cheers,

Sorin Peste




More information about the Mono-devel-list mailing list