mbdavid / LiteDB

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

[BUG] #2262

Closed Gabisonfire closed 1 year ago

Gabisonfire commented 1 year ago

Version Which LiteDB version/OS/.NET framework version are you using. (REQUIRED) LiteDB 5.0.12, .net 7

Describe the bug Insert returns

E 0:00:00.845   LiteDB.BsonValue LiteDB.LiteCollection`1[[Card, projectDeck, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].Insert(Card ): System.NullReferenceException: Object reference not set to an instance of an object.

On what seems to be a very simple insert.

Code to Reproduce Card.cs

public enum CardType { Action, Attack, Defense, None }

public class Card
{
    public string Name {get;}
    public int Id {get;}
    public CardType CardType {get;}
}

DB.cs

public static class DB {
    static LiteDatabase db;
    public static void Init(){
        db = new LiteDatabase(Tunables.DBName);
    }

    public static void Insert<T>(T toInsert, string collectionName)
    {
        using(db)
        {
            var collection = db.GetCollection<T>(collectionName);
            collection.Insert(toInsert);
        }
    }

main.cs

    public static void main()
    {
        DB.Init();
        var card = new Card("test", CardType.Action);
        DB.Insert(card, "Cards");
    }

I can see using LiteDBStudio that the document still gets inserted into the database.

Expected behavior Insert not to throw an error.

Screenshots/Stacktrace

E 0:00:00.845   LiteDB.BsonValue LiteDB.LiteCollection`1[[Card, projectDeck, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].Insert(Card ): System.NullReferenceException: Object reference not set to an instance of an object.
  <C++ Error>   Unhandled exception
  <C++ Source>  :0 @ LiteDB.BsonValue LiteDB.LiteCollection`1[[Card, projectDeck, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].Insert(Card )()
  <Stack Trace> :0 @ LiteDB.BsonValue LiteDB.LiteCollection`1[[Card, projectDeck, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].Insert(Card )()
                DB.cs:16 @ void DB.Insert<Card >(Card , System.String )()
                MainController.cs:13 @ void MainController._Ready()()

Additional context

Gabisonfire commented 1 year ago

Found the issue a few minutes after posting, seems like objects inserted cant have a null value, in my example, id was not set by the constructor, therefore null. Giving a value resolved that issue.