【问题标题】:Linq2db: join tables with eager loadingLinq2db:使用急切加载连接表
【发布时间】:2020-12-20 06:16:55
【问题描述】:

我在我的项目中使用 linq2db ORM 并具有以下数据库架构(简化):

我有以下方法来获取有关用户的信息:

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;
}

但是,我想获取有关每个帐户的所有限制和聚合器的信息。我相信应该有一种有效的方法来做到这一点。有人可以帮我吗?

【问题讨论】:

    标签: c# linq2db


    【解决方案1】:

    当我们使用LoadWith()时,在使用ThenLoad()之后,它将从根(User表)开始,像这样:

    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);
    

    您也可以使用Include()ThenInclude() 代替LoadWith()ThenLoad()Include vs Load.

    【讨论】:

    • 不能使用Inlucde,linq2db和EF是不同的ORM,EF中使用Include()。
    • 但是,您的方法给了我一个有用的提示,我可以解决这个问题。谢谢。
    • 你是对的。我很高兴它对你有用。
    最近更新 更多