【问题标题】:How do I limit the number of results back in LinqToSql?如何限制 LinqToSql 中的结果数量?
【发布时间】:2010-11-20 02:57:51
【问题描述】:

我习惯于使用LoadWith 语法加载一些子结果(对于父结果)。效果很好。有没有办法可以将这些 LoadWith 结果限制为最近的 5 个或其他什么?

我有一些带有一些内联 cmets 的伪代码来帮助解释我正在尝试做什么......

例如。

IList<Parent> results;

using (DataBaseContext db = new MyDb())
{
    var dlo = new DataLoadOptions();
    dlo.LoadWith<Parent>(x => x.Child1);  // We only want the most recent 10.
    dlo.LoadWith<Parent>(x => x.Child2);  // All of these...
    dlo.LoadWith<Parent>(x => x.Child3);  // Only the most recent 1.
    db.LoadOptions = dlo;

    results = (from p in Parent
               orderby p.Id descending
               select p).Take(5).ToList();
}

干杯:)

【问题讨论】:

标签: .net linq-to-sql


【解决方案1】:

这应该可行,假设您将排序顺序设置为有意义的。 (DataLoadOptions.AssociateWith() Reference)

IList<Parent> results;

using (DataBaseContext db = new MyDb())
{
    var dlo = new DataLoadOptions();
    dlo.LoadWith<Parent>(x => x.Child1);  // We only want the most recent 10.
    dlo.AssociateWith<Parent>(x => x.Child1.OrderByDescending(c => c.Date).Take(10));
    dlo.LoadWith<Parent>(x => x.Child2);  // All of these...
    dlo.LoadWith<Parent>(x => x.Child3);  // Only the most recent 1.
    dlo.AssociateWith<Parent>(x => x.Child3.OrderByDescending(c => c.Date).Take(1));
    db.LoadOptions = dlo;

    results = (from p in Parent
               orderby p.Id descending
               select p).Take(5).ToList();
}

纯克罗姆编辑

请注意(任何读过这篇文章的人)如果你使用 AssociateWith 方法,你必须在它前面加上一个 LoadWith。注意我们如何 LoadWith(child1) 和下一行 AssociateWith(..some funky-ass lambda) ??很好 -> 如果您忘记在 AssociateWith 之前放入 LoadWith,则不会生成任何 sql,并且不会为该孩子返回任何内容。

【讨论】:

  • 喷!有用!!我一直想知道 AssociateWith 是/是/是什么。 酱汁真棒。谢谢你,瑞安。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 2019-11-09
相关资源
最近更新 更多