1) You can insert it the way @Tim Skauge does. But while selecting the .Net connector version is important. When I had used v 5.2.1, I needed to do only this:
using (MySqlCommand cmd = new MySqlCommand("SELECT id FROM test", conn))
{
using (MySqlDataReader r = cmd.ExecuteReader())
{
r.Read();
Guid id = (Guid)r[0];
}
}
Here the reader itself reads the binary value to .NET Guid type. You can see it if you check the type of r[0]. But with newer version, ie, 6.5.4, I found the type to be byte[].. ie, it gets the binary value from db to its corresponding byte array. So you do this:
using (MySqlCommand cmd = new MySqlCommand("SELECT id FROM test", conn))
{
using (MySqlDataReader r = cmd.ExecuteReader())
{
r.Read();
Guid id = new Guid((byte[])r[0]);
}
}
You can read why is it so here in documentation. The alternative to read Guid type directly and not as byte[] is to have this line : Old Guids=true in your connection string.
2) Additionally you can do this straight away to read the binary value as string by asking MySQL to do the conversion, but in my experience this method is slower.
Insert:
using (var c = new MySqlCommand("INSERT INTO test (id) VALUES (UNHEX(REPLACE(@id,'-','')))", conn))
{
c.Parameters.AddWithValue("@id", Guid.NewGuid().ToString());
c.ExecuteNonQuery();
}
or
using (var c = new MySqlCommand("INSERT INTO test (id) VALUES (UNHEX(@id))";, conn))
{
c.Parameters.AddWithValue("@id", Guid.NewGuid().ToString("N"));
c.ExecuteNonQuery();
}
And select:
using (MySqlCommand cmd = new MySqlCommand("SELECT hex(id) FROM test", c