低效“任何” LINQ 子句
我有一个查询可以拉回用户的“提要”,这基本上是他们的所有活动。如果用户登录,查询将被过滤,以便提要不仅包括指定用户的所有数据,还包括他们的任何朋友。
数据库结构包括一个 Actions 表和一个 UserFriends 表,前者保存创建该操作的用户,后者使用映射到 UserIds 的 FrienderId 和 FriendeeId 列保存任何好友配对。
我已经设置了 LINQ 查询,它可以很好地拉回我想要的数据,但是,我注意到查询在探查器中变成了 X 个 CASE 子句,其中 X 是数据库中的总操作数。当数据库的用户群大于我和 3 个测试用户时,这显然会很可怕。
这是我想要实现的 SQL 查询:
select * from [Action] a
where a.UserId = 'GUID'
OR a.UserId in
(SELECT FriendeeId from UserFriends uf where uf.FrienderId = 'GUID')
OR a.UserId in
(SELECT FrienderId from UserFriends uf where uf.FriendeeId = 'GUID')
这是我当前的 LINQ 查询。
feed = feed.Where(o => o.User.UserKey == user.UserKey
|| db.Users.Any(u => u.UserFriends.Any(ufr => ufr.Friender.UserKey ==
user.UserKey && ufr.isApproved)
|| db.Users.Any(u2 => u2.UserFriends.Any(ufr => ufr.Friendee.UserKey ==
user.UserKey && ufr.isApproved)
)));
此查询创建: http://pastebin.com/UQhT90wh
在配置文件跟踪中显示 X 次,每个操作一次桌子。我做错了什么?有什么办法可以清理这个吗?
I have a query that pulls back a user's "feed" which is essentially all of their activity. If the user is logged in the query will be filtered so that the feed not only includes all of the specified user's data, but also any of their friends.
The database structure includes an Actions table that holds the user that created the action and a UserFriends table which holds any pairing of friends using a FrienderId and FriendeeId column which map to UserIds.
I have set up my LINQ query and it works fine to pull back the data I want, however, I noticed that the query gets turned into X number of CASE clauses in profiler where X is the number of total Actions in the database. This will obviously be horrible when the database has a user base larger than just me and 3 test users.
Here's the SQL query I'm trying to achieve:
select * from [Action] a
where a.UserId = 'GUID'
OR a.UserId in
(SELECT FriendeeId from UserFriends uf where uf.FrienderId = 'GUID')
OR a.UserId in
(SELECT FrienderId from UserFriends uf where uf.FriendeeId = 'GUID')
This is what I currently have as my LINQ query.
feed = feed.Where(o => o.User.UserKey == user.UserKey
|| db.Users.Any(u => u.UserFriends.Any(ufr => ufr.Friender.UserKey ==
user.UserKey && ufr.isApproved)
|| db.Users.Any(u2 => u2.UserFriends.Any(ufr => ufr.Friendee.UserKey ==
user.UserKey && ufr.isApproved)
)));
This query creates this:
http://pastebin.com/UQhT90wh
That shows up X times in the profile trace, once for each Action in the table. What am I doing wrong? Is there any way to clean this up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会将查询分为两个查询,
这是我在不知道你确切的接口和对象的情况下进行的尝试,但它显示了这个概念:
这应该会产生类似于此的查询
I would split the query into two queries,
Here is my shot at it without knowing your exact itnerfaces and ojbects, but it shows the concept:
This should yield a query similar to this