mbdavid / LiteDB

LiteDB - A .NET NoSQL Document Store in a single data file
http://www.litedb.org
MIT License
8.35k stars 1.22k forks source link

[BUG] Empty Fields are Serialized as null #2492

Closed JKamsker closed 3 weeks ago

JKamsker commented 3 weeks ago

Version Which LiteDB version/OS/.NET framework version are you using. Latest

Describe the bug When writing an object with a whitespace string into the database, it gets serialized as null.

Code to Reproduce

  private class DataClass
    {
        [BsonId]
        public int Id { get; set; }

        public string Foo { get; set; }

        public string Bar { get; set; }
    }

    [Fact]
    public void TestEmptyStrings()
    {
        using var db = new LiteDatabase(":memory:");
        var collection = db.GetCollection<DataClass>("data");

        collection.Insert(new DataClass { Foo = "bar", Bar = "abc" });
        collection.Insert(new DataClass { Foo = " ", Bar = "def" });

        var defAction = () => collection.FindOne(x => x.Foo == " ");

        defAction.Should().NotThrow();

        var def = collection.FindOne(x => x.Foo == " ");
        def.Should().NotBeNull();
        def.Bar.Should().Be("def");
    }

Expected behavior Should be serialized as empty string

JKamsker commented 3 weeks ago

Funny. There is a setting to fix this.

Why on earth is this the default setting?

  BsonMapper.Global.EmptyStringToNull = false;
  BsonMapper.Global.TrimWhitespace = false;