Search code examples
ormlite-servicestack

How can I get all the objects associated through the intermediate table by ServiceStack.OrmLite?


I'm a beginner who has just started using ServiceStack.OrmLite. I have a question. How can I get all the objects associated through the intermediate table?

details as following:

Public class book
{
    Public int id { get; set; }
    Public string name { get; set; }
    [Reference]
    Public List<bookusers> bookusers { get; set; }
}

Public class bookusers
{
    Public int id { get; set; }
    Public int bookid { get; set; }
    Public int userid { get; set; }
    [Reference]
    Public book book { get; set; }
    [Reference]
    Public user userObject { get; set; }
}

Public class user
{
    Public int id { get; set; }
    Public int age { get; set; }
    [Reference]
    Public List<bookusers> userbooks { get; set; }
}

var model = db.LoadSingleById<book>(id);
db.LoadReferences(model);
// model.bookusers[0].userObject is null

Solution

  • You can't directly retrieve second level references as stated in documentation.

    Loads related data only 1-reference-level deep

    A quick and dirt working method could be the next

    var model = db.LoadSingleById<book>(id);
    if (model.bookusers != null && model.bookusers.Any())
    {
        foreach (var bookUser in model.bookusers)
        {
            db.LoadReferences(bookUser);
        }
    }
    

    Then you should have your userObject property populated.