从 IQueryable获取映射行在 Linq2Sql 中
情况是:网页向登录用户显示聚会列表。此可查询组中可能有用户已订阅但在加载此页面之前尚未查看的聚会。既然该用户已经查看了聚会,我想将其标记为这样。
我可以通过使用 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 次?
The situation is: a webpage displays a listing of Gatherings to a logged-in user. Among this Queryable group might be Gatherings that the user is subscribed to but has not yet viewed until loading this page. Now that the Gatherings have been viewed by this user, I want to mark them as such.
I can get this to work by using ToList() and Contains() (see below) but that means I have to make 2 trips to the database: 1 for ToList() and 1 for foreach(). I've tried other ways to get these Subscriptions but they end up as EntitySet instead.
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();
}
How can I achieve the same thing but with only 1 trip to the database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与此处相同的问题: linq 问题:查询嵌套集合
解决方案是更改此设置:
对此:
Same problem as here: linq question: querying nested collections
The solution is to change this:
to this: