Binary Data as Primary Key?

J

jgbeldock

Hi.

A colleague of mine is trying to use an eight-byte array as the
primary key into an ADO.NET DataTable, but he's getting exceptions
thrown when he attempts to set the appropriate column as the primary
key. Here's his sample:

public static void ByteArrayKey () {
DataTable dt = new DataTable();
dt.Columns.Add (new
DataColumn("bytes",typeof(System.Byte[])));

DataRow dr = dt.NewRow();
dr["bytes"] = new System.Byte[]
{0,1};
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["bytes"] = new System.Byte[]
{1,0};
dt.Rows.Add(dr);
try {
dt.PrimaryKey = new
DataColumn[]{dt.Columns[0]};
System.Console.WriteLine("Set primaryKey as byte
array");
} catch (System.ArgumentException e) {
System.Console.WriteLine("Could not set primaryKey as
byte array: {0}",
e.ToString());
}

}

This code will result in the exception being thrown. There *IS* a
SqlDbType.Binary which is what we really want here, but I can't seem
to find the appropriate System.Type to suggest as the DataColumn type
to avoid the exception.

Anyone have ideas?

Thanks,
/s/ James
 
R

Ravi[MSFT]

The reason you are seeing the exception is because dataset does not
understand byte arrays. For that matter dataset does not understand any type
of arrays or user defined types. Anything other that "CLR primitive types +
some additional types like GUID" would be converted to a string with
ToString(). When you do a ToString() on any byte[] you woud see the type
name itself [since ToString() on byte[] is not overridden] something like
"System.Byte[]". Since all the rows would basically have the string
"System.Byte[]" it violates the PK constraint. In the next version, all the
columns will be strongly typed[in that the runtime data will not be diluted
to a string as it happening in 1.0/1.1]. So placing a constarint like PK on
Byte[] columns would be possible in the next version but is a limitation in
the current.

Thanks,
Ravi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top