Possible Duplicate:
How should I store GUID in MySQL tables?
VARCHAR will return as string
BLOB will return as byte[]
but, what column type of MySQL will return as System.Guid in C#
thanks.
Edited: I have found the answer
thanks to DaveHogan that gives me the clue about ORM (Object Relation Mapping)
I started to look for information about the datatype conversion(mapping) made by Connector/NET.
I'm using MySQL Dot Net Connector (Connector/NET)
there are different 3 situations that Connector/NET performs.
Below are what I have found:
1st Situation:
Start from Connnector/NET 6.1.1, CHAR(36) will be automatically converted as System.GUID in C# and BINARY(16) will be treated as System.Byte[].
2nd Situation:
If you use older Connector/NET, BINARY(16) will be automatically converted as System.GUID when the value is passed into C# and CHAR(36) will be treated as System.String.
3rd Situation:
If you use newer Connector/NET (newer than 6.1.1), and if you want to use BINARY(16) AS System.GUID (be default it is not), you have to add a connection option Old Guids=true in the Connection String.
Example:
server=localhost;user=root;password=qwerty;database=test;old guids=true;
by this, CHAR(36) will be converted as System.String and BINARY(16) = System.GUID
Read more about connection options of Old Guids at:
MySQL 5.6 Reference Manual: 21.2.6. Connector/Net Connection String Options Reference
----------------------------------------------------------------------
Extra Info:
How to Insert System.GUID into MySql Database
----------------------------------------------------------------------
This is a sample table, that we are going to insert the System.GUID:
CREATE TABLE `testdata` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `binary` binary(16) DEFAULT NULL, `char` char(36) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
Insert System.GUID into MySQL
string constr = "server=localhost;user=root;pwd=qwerty;database=test;"; using (MySqlConnection conn = new MySqlConnection(constr)) { conn.Open(); // Create a System.GUID byte[] ba = new byte[16]; Random rd = new Random(); rd.NextBytes(ba); System.Guid guid = new Guid(ba); // Prepare GUID values in SQL format string guidForChar36 = guid.ToString(); string hexstring = BitConverter.ToString(guid.ToByteArray()); string guidForBinary16 = "0x" + hexstring.Replace("-", string.Empty); string sql = "insert into testdata(`binary`,`char`)" + "values(" + guidForBinary16 + "," + "'" + guidForChar36 + "');"; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.ExecuteNonQuery(); conn.Close(); }
EDIT:
Sorry I misunderstood your question. You should use
BINARY(16)
How you cast that to a System.Guid depends on whether you're using an ORM etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With