litedbulong

ulong is not be stored correctly in LiteDatabse


I am now making a MMO game using Unity. Also I am using the LiteDB to store users data. UserModel looks like this. UserModel of my game

Everything is working correctly except for the mUserOwnerClientId. The variable type is ulong and I tried to store ulong.MaxValue. But the stored value was -1 and when I tried to read from database, there was an error because ulong could not be less than zero.

When I store ulong.MaxValue, it is stored as -1

So I have a question here.

Does LiteDB support ulong storing?


Solution

  • LiteDB supports long by default, not ulong (unsigned).

    But you can tell it how to handle the serialization and deserialization of a type it doesn't know with BsonMapper before using your database:

    BsonMapper.Global.RegisterType<ulong>(
        unsignedLong => new BsonValue(unsignedLong.ToInt64WithSameBits()),
        bson => bson.AsInt64.ToUInt64WithSameBits()
    );
    
    /// <summary>
    /// Extra methods for <see cref="ulong"/> type.
    /// </summary>
    public static class UInt64ExtensionMethods
    {
        /// <summary>
        /// Takes the bits of the provided <see cref="ulong"/> value and returns them as a <see cref="long"/>, which might be a completely different number.
        /// </summary>
        /// <remarks>
        /// See https://stackoverflow.com/questions/13056230/copy-bits-from-ulong-to-long-in-c-sharp .
        /// </remarks>
        public static long ToInt64WithSameBits(this ulong value)
        {
            return unchecked((long) value);
        }
    }
    

    Then when you want to use queries you can use the BsonMapper again:

    ulong playerID = 1234;
    var query = Query.EQ(nameof(PlayerDocument.PlayerID), BsonMapper.Global.Serialize(playerID));