简体   繁体   中英

Linq2db: join tables with eager loading

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

在此处输入图像描述

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM