Binary Data as Primary Key?




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

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


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?

/s/ James


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.


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