Search code examples
c#.netlitedb

Unable to store and retrieve data from LiteDb


I am trying to write one object to LiteDb and read it back. I have tried following code but somehow all parameters of LiteDbParamEntry object are returned as NULL or zero.

public class LiteDbParamEntry
{
    [BsonId]
    public int Id
    {
        get { return (Index * 0x100) + SubIndex; }
    }

    public ushort Index;

    public ushort SubIndex;

    public string Text;
}

public class LiteDbParamValueStorage
{
    private const string _liteDbPath = "MyLiteData.db";

    public LiteDbParamValueStorage()
    {
        WriteEntry(123, 25);
        ReadEntry(123, 25);
    }

    public void WriteEntry(ushort index, ushort subIndex)
    {
        using (var db = new LiteDatabase(_liteDbPath))
        {
            var entry = new LiteDbParamEntry {Index = index, SubIndex = subIndex, Text = "SomeText"};

            var entries = db.GetCollection<LiteDbParamEntry>("LiteDbParamEntry");

            entries.Insert(entry);
        }
    }

    public void ReadEntry(ushort index, ushort subIndex)
    {
        using (var db = new LiteDatabase(_liteDbPath))
        {
            var collection = db.GetCollection<LiteDbParamEntry>("LiteDbParamEntry");
            var paramEntry = collection.FindById((index * 0x100) + subIndex);
            if (paramEntry != null)
                Console.WriteLine(paramEntry.Text);          //paramEntry.Text is returned as Null
            else
                return;
        }
    }
}

Can somebody please point me in right direction?


Solution

  • Finally, i've found what's wrong with your code... You forgot to add { get; set; } instruction on the right side of field declaration ;)

    Take a look here:

    public class LiteDbParamEntry
    {
        [BsonId]
        public int Id
        {
            get { return (Index * 0x100) + SubIndex; }
        }
    
        public ushort Index { get; set; } //getter/setter added
    
        public ushort SubIndex  { get; set; } //getter/setter added
    
        public string Text  { get; set; } //getter/setter added
    }
    

    Good luck!