1

I am trying to save collection of the strings to LiteDb

using (var db = new LiteDatabase(@"MyData.db"))
{
    var col = db.GetCollection<string>("Writers");
    col.Insert("Mark Twain");
    col.Insert("Jack London");
 }

It throws "Object reference not set to an instance of an object." at LiteDB.BsonMapper.ToDocument[T](T entity) on Insert.

Code like this works:

public class Writer
{
    public string Name { get; set; }
}

using (var db = new LiteDatabase(@"MyData.db"))
{
    var col = db.GetCollection<Writer>("Writers");
    col.Insert(new Writer { Name = "Mark Twain" });
    col.Insert(new Writer { Name = "Jack London" });
}

Why? What's wrong with the string?

Just Me
  • 41
  • 1
  • 8
  • 2
    It is not a duplication of "What is a NullReferenceException". Null reference is in LiteDb code. – Just Me Oct 11 '17 at 21:11
  • @rene. No. There are no "Writers" collection in my Db. I tried with empty database. Result is the same. – Just Me Oct 11 '17 at 21:17
  • 1
    @rene. It works with the Writer class. It does not work with the string. – Just Me Oct 11 '17 at 21:21
  • 1
    Maybe it's because strings are immutable in C#. There are only 2 options: you can try look through the code of BsonMapper or ask LiteDb developers. – Valerii Oct 11 '17 at 21:56

1 Answers1

3

LiteDB is a "Document Store" database, so you can only store documents. You can't store inside a collection any primitive data type or array.

Document structure is required because each document must contains an unique _id value field. If you do not provide (like in your example), LiteDB will auto create this Id field using ObjectId.

If you want avoid create this class, you can use BsonDocument to be more simple to use.

using (var db = new LiteDatabase(@"MyData.db"))
{
    var col = db.GetCollection("Writers");
    col.Insert(new BsonDocument { ["Name"] = "Mark Twain" });
    col.Insert(new BsonDocument { ["Name"] = "Jack London" });
}
mbdavid
  • 1,076
  • 7
  • 8