从IQueryable获取映射行<;外键>;在Linq2Sql中
这种情况是:一个网页向一个登录的用户显示一个聚会列表。此可查询组中可能有用户已订阅但在加载此页面之前尚未查看的集会。现在,该用户已经查看了这些聚会,我想将它们标记为这样 我可以通过使用ToList()和Contains()来实现这一点(见下文),但这意味着我必须对数据库进行两次访问:1次用于ToList(),1次用于foreach()。我尝试了其他方法来获取这些订阅,但它们最终成为EntitySet从IQueryable获取映射行<;外键>;在Linq2Sql中,linq,linq-to-sql,iqueryable,Linq,Linq To Sql,Iqueryable,这种情况是:一个网页向一个登录的用户显示一个聚会列表。此可查询组中可能有用户已订阅但在加载此页面之前尚未查看的集会。现在,该用户已经查看了这些聚会,我想将它们标记为这样 我可以通过使用ToList()和Contains()来实现这一点(见下文),但这意味着我必须对数据库进行两次访问:1次用于ToList(),1次用于foreach()。我尝试了其他方法来获取这些订阅,但它们最终成为EntitySet Users Gatherings ===== ========== UserId
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();
}
用户聚会
===== ==========
用户ID GatheringId
收集订阅
======================
GatheringSubscriptionId
采集ID
用户ID
观看
//update unviewed=>已查看此用户对每个
//在这些聚会中
已查看公共无效标记(IQueryable gatherings,int userId){
List gIdsList=gatherings.Select(g=>g.GatheringId.ToList();
IQueryable gSubs=db.GatheringSubscriptions
.其中(gs=>
gs.UserId==UserId&&
!gs.isview&&
gIdsList.Contains(gs.GatheringId))
.Distinct();
foreach(在gSubs中收集订阅gSub)
gSub.isview=true;
db.SubmitChanges();
}
如何实现相同的目标,但只需访问数据库一次?与此处相同的问题:
解决方案是改变这一点:
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();