Guid.Tostring() gives a different representation than UUID_TO_CHAR in my database

Viewed 536

I'm using a Firebird database with UUIDs as primary keys but I've run into the following problem:

The textual representation of the same Guid in my C# application differs from that of the database. I'm getting the textual representation in the database with the UUID_TO_CHAR function and in my C# application using Guid.ToString().

The difference comes from the way the Firebird database interprets the UUIDs vs the .net framework, I believe they read them with a different byte ordering

So for example a guid in the database looks like this:

FADE3E40-6227-5B40-BBB9-8492859EBA66

And the same guid in my C# application looks like this:

403edefa-2762-405b-bbb9-8492859eba66

Is there a way to either display them in my database the same way they're displayed in C#. Or vice versa?

Is there a way to do a conversion when getting them from, and putting them into, the database so I don't have to use a format anywhere?

1 Answers

To get the same representation as in firebird - convert all bytes of guid as is to hex:

BitConverter.ToString(guid.ToByteArray()).Replace("-", "")

You can optionally put "-" between groups if necessary, for example like this:

static class Extensions {
    public static string ToFirebirdString(this Guid guid) {
        var raw = BitConverter.ToString(guid.ToByteArray()).Replace("-", "");
        return $"{raw.Substring(0, 8)}-{raw.Substring(8, 4)}-{raw.Substring(12,4)}-{raw.Substring(16, 4)}-{raw.Substring(20)}";
    }
}
Related