【问题标题】:Getting mapped rows from IQueryable<ForeignKey> in Linq2Sql从 Linq2Sql 中的 IQueryable<ForeignKey> 获取映射行
【发布时间】:2011-01-01 07:52:00
【问题描述】:

情况是:网页向登录用户显示聚会列表。在这个 Queryable 组中可能有用户订阅但在加载此页面之前尚未查看的 Gatherings。现在该用户已经查看了聚会,我想将它们标记为此类。

我可以通过使用 ToList() 和 Contains()(见下文)使其工作,但这意味着我必须对数据库进行 2 次访问:1 次用于 ToList(),1 次用于 foreach()。我尝试了其他方法来获取这些订阅,但它们最终变成了 EntitySet。

Users     Gatherings
=====     ==========
UserId    GatheringId

GatheringSubscriptions
======================
GatheringSubscriptionId
GatheringId
UserId
IsViewed

// update unviewed=>viewed for this user's subscription to each
// of these gatherings
public void MarkViewed(IQueryable<Gathering> gatherings, int userId) {
    List<int> gIdsList = gatherings.Select(g => g.GatheringId).ToList();
    IQueryable<GatheringSubscription> gSubs = db.GatheringSubscriptions
        .Where(gs =>
            gs.UserId == userId &&
            !gs.IsViewed &&
            gIdsList.Contains(gs.GatheringId))
        .Distinct();
    foreach (GatheringSubscription gSub in gSubs)
        gSub.IsViewed = true;
    db.SubmitChanges();
}

我怎样才能实现相同的目标,但只需要访问数据库 1 次?

【问题讨论】:

    标签: linq linq-to-sql iqueryable


    【解决方案1】:

    与此处相同的问题:linq question: querying nested collections

    解决办法是改变这个:

    db.GatheringSubscriptions
        .Where(gs =>
            gs.UserId == userId &&
            !gs.IsViewed &&
            gIdsList.Contains(gs.GatheringId))
        .Distinct();
    

    到这里:

    tickers.SelectMany(t => t.GatheringSubscriptions)
        .Where(gs =>
            gs.UserId == userId &&
            !gs.IsViewed)
        .Distinct();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2020-12-22
      • 2021-05-06
      相关资源
      最近更新 更多