Linq2db: join tables with eager loading

1.5k Views Asked by At

I'm using linq2db ORM in my project and have the following database schema (simplified):

enter image description here

I have the following method to get information about the user:

public async Task<User> GetUser(int id)
{
  var user =
    await (
        from u in _db.Users
                     .LoadWith(u => u.Accounts)
                     .ThenLoad(a => a.Transactions)
        where u.Id == id
        from lang in _db.Languages.LeftJoin(l => l.Id == u.LanguageId)
        select u)
      .FirstOrDefaultAsync();

  return user;
}

However, I wanted to get the information about all the limits and aggregators for each account. I believe there should be an efficient way to do that. Could someone help me with that?

1

There are 1 best solutions below

3
On BEST ANSWER

When we use LoadWith(), after using ThenLoad(), it's going to start from the root (User table), like this:

from u in _db.Users
                 .LoadWith(u => u.Accounts)
                    .ThenLoad(a => a.Transactions)
                 .LoadWith(u => u.Accounts)
                    .ThenLoad(a => a.Limits)
                 .LoadWith(u => u.Accounts)
                    .ThenLoad(a => a.Aggregators);

You can also use Include() and ThenInclude() instead of LoadWith() and ThenLoad(). Include vs Load.