1

I'm testing LiteDB database but have an issue on updating a data. Let's consider the source code:

    public class Session
    {
        [BsonId]
        public int Id { get; set; }
        public Guid SessionGuid { get; set; }
        public DateTime Date { get; set; }
        public double TotalAmount { get; set; }

        [BsonRef("paymentInfos")]
        public PaymentInfo PaymentInfos { get; set; }
    }

    public class PaymentInfo
    {
        [BsonId] 
        public int Id { get; set; }
        public string Type { get; set; }
        public double Amount { get; set; }    
    }

_database = new LiteDatabase(databasePath);

var sessions = _database.GetCollection<Session>("sessions");

var sessionId = Guid.NewGuid();
var session = new Session
{
    SessionGuid = sessionId,
    Date = Datetime.Now
};
sessions.Insert(session);


var sessions = _database.GetCollection<Session>("sessions");
var session = sessions.FindOne(x => x.SessionGuid == sessionId);

var paymentInfo = new PaymentInfo
{
    Type = "Coin",
    Amount = 2.0,
};

var paymentInfos = _database.GetCollection<PaymentInfo>("paymentInfos");
paymentInfos.Insert(paymentInfo);

session.PaymentInfos = paymentInfo;
sessions.Update(session);

session = sessions.FindOne(x => x.SessionGuid == sessionId);
var paymentAmount = session.PaymentInfos.Amount;

I was expecting that the paymentAmount will be 2.0, but it is only 0. It's like only the session.PaymentInfos.Id is good but all other properties have been lost. Is something wrong with my session update ? Maybe I've missed something ?

Thanks in advance.

Gizmo
  • 66
  • 2
  • 7

1 Answers1

1

When working with collection references, you need to Include the other collection: sessions.Include(x=>x.PaymentInfos).FindOne(x => x.SessionGuid == sessionId)

The LiteDb documentation describes the behavior you are seeing:

If you do not use Include in query, classes are loaded with only ID set (all other properties will stay with default/null value).

That being said it may be better to avoid using DbRef. LiteDb is a non-relational database, so it benefits from different patterns than a traditional SQL database. To quote a Stack Exchange answer about NoSql best practices:

Appropriate approach for NoSQL database design is a DDD (Domain Driven Design ). For some people who used to design RDBMS, NoSql looks like Sql anti-patterns and it make more sense when considered in a scope of a DDD.

When I first switched from SQL to LiteDB, I started by using DbRef and seperate collections for everything. Over time I got more practice thinking non-relationally, and I discovered that use-case I was working on (relationships between objects positioned in 3d space) could be modelled more accurately by storing information inside the objects, rather than using a separate collection and DbRef.

hedberggames
  • 116
  • 4