Pergunta

Ok I have a GUID f5cc4100-f1b4-4af6-9e9e-224b0eb74166 and I am inserting it to MySQL database using the ADO .NET Connector.

I can do it in two ways:

1) Feed byte array to .NET Connector

string query = "insert into test (pk_id) values (@id)";
using (var c = new MySqlCommand(query, conn))
{
    c.Parameters.AddWithValue("@id", new Guid("f5cc4100-f1b4-4af6-9e9e-224b0eb74166").ToByteArray());
    c.ExecuteNonQuery();
}

2) Rely on MySQL standard function to convert hexadecimal to binary string.

string query = "insert into test (pk_id) values (UNHEX(@id))";
using (var c = new MySqlCommand(query, conn))
{
    c.Parameters.AddWithValue("@id", "f5cc4100-f1b4-4af6-9e9e-224b0eb74166".Replace("-", "");
    c.ExecuteNonQuery();
}

The problem I face is the two above methods inserts the same guid in slightly different character order.

If I am selecting back the inserted guid like this:

string query = "select PK_id from test";
using (var c = new MySqlCommand(query, conn))
{
    using (var r = c.ExecuteReader())
    {
        while (r.Read())
        {
            var k = new Guid((byte[])r[0]);
        }
    }
}

I get f5cc4100-f1b4-4af6-9e9e-224b0eb74166 and 0041ccf5-b4f1-f64a-9e9e-224b0eb74166 back. But if I am reading like this:

string query = "select hex(PK_id) from test";
using (var c = new MySqlCommand(query, conn))
{
    using (var r = c.ExecuteReader())
    {
        while (r.Read())
        {
            var k = new Guid((string)r[0]);
        }
    }
}

I get 0041ccf5-b4f1-f64a-9e9e-224b0eb74166 and f5cc4100-f1b4-4af6-9e9e-224b0eb74166.

In short, if I am inserting the GUID as bytearrays, then I need to read them as such and cast as byte arrays to get the right GUID. And if I am inserting the GUID as UNHEX of the hexadecimal guid string, then I need to read from db using its equivalent HEX function.

  1. Why are writing and reading different with the above two methods?

  2. What would be the more appropriate way of handling GUIDs between the two?

Foi útil?

Solução

Since the Original Poster asked for my comments (which are just links) to be posted as an answer, here it comes:

SO: Guid Byte Order in .NET

MSDN: System.Guid .ToByteArray swapping first 4 bytes

SO: C#: Why isn't Guid.ToString(“n”) the same as a hex string generated from a byte array of the same guid?

It seems like it's not clearly documented what endianness the different components of the Guid possess, when converting to and from Byte[].

Outras dicas

Nielsen answers one part of the question. As to which to use, there is nothing that makes a good choice. Either way it fine. If the values in the db will be required to read later outside the .NET world, then MySQL hexing and unhexing will be better. There is a slight (very very slight) performance penalty associated with hexing and unhexing in my tests. If it matters for you, then stick with ToByteArray()

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top