0

状況は次のとおりです。Web ページは、ログインしているユーザーにギャザリングのリストを表示します。このクエリ可能なグループの中には、ユーザーが購読しているが、このページをロードするまでまだ表示されていないギャザリングが含まれる場合があります。ギャザリングがこのユーザーによって表示されたので、そのようにマークしたいと思います。

ToList() と Contains() (以下を参照) を使用してこれを機能させることができますが、これはデータベースに 2 回アクセスする必要があることを意味します。これらのサブスクリプションを取得する他の方法を試しましたが、代わりに 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 回だけです。

4

1 に答える 1

0

ここと同じ問題:linq質問:ネストされたコレクションのクエリ

解決策はこれを変更することです:

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();
于 2010-01-04T18:18:42.723 に答える