简体   繁体   English

Linq to Entities Count子查询

[英]Linq to Entities Count subquery

Okay so I've got a bunch of places which users can rate (give a score). 好的,我有很多地方可供用户评分(给出分数)。 When fetching places I also want to know how many of my friends rated that place. 在获取地点时,我还想知道有多少朋友评价了该地点。 Users become friends by sending requests. 用户通过发送请求成为朋友。

FRIENDREQID -- ID of user that sent the request.
FRIENDRESPID -- ID of user that got the request
STATUS -- Status of the request. (Accepted / Pending)

This query does the job. 这个查询完成了工作。

select 
    p.*,
    (
        select 
            count(*) 
        from 
            UserRatings ur, 
            Friends f 
        where 
            ur.PlaceId = p.PlaceId
            and (ur.UserId = f.FriendReqId and f.FriendRespId = @myUserId ) 
            or  (ur.UserId = f.FriendRespId and f.FriendReqId = @myUserId ) 
            and f.Status = 'A' 
    ) as FriendCount
from 
    Places p

I really struggled with coming up with a mutual query in linq to entities (I'm a beginner) and came up with this. 我真的很难在linq中对实体(我是初学者)提出一个相互查询,并提出了这个建议。

 var result = (from p in db.Places
                 select new PlaceDTO
                 {
                     PlaceId = p.PlaceId,
                     FriendRatingCount = (from f in db.Friends
                                          from ur in db.UserRatings
                                          where ur.PlaceId == p.PlaceId && 
                                                (ur.UserId == f.FriendReqId && f.FriendRespId == argUserId) ||
                                                (ur.UserId == f.FriendRespId && f.FriendReqId == argUserId) &&
                                                f.Status == "A" 
                                          select f).Count()
                 })

Is it my friend system model that makes this query a bit bulky? 是我的朋友系统模型使此查询有点笨重吗? Anyone has any tip of approvements that can be done too make it more efficient, easily read? 任何人都有可以完成的一些小技巧,也可以使其更有效,更容易阅读?

One question - why are you recalculating friends for every query? 一个问题-为什么您要为每个查询重新计算朋友? You can figure out the friends, and put reference to them in the User object. 您可以找出朋友,并在User对象中引用他们。 It's much simpler to do 这要容易得多

var friendPlaces = users.Friends.Reviews.Where(r => r.PlaceId == placeID);

or even better 甚至更好

var friendPlace= users.Friends.Select(GetPlacesReviewed).Where(p => p.Id == placeID);

than have every part of the application know about your basic DB structure. 而不是让应用程序的每个部分都了解您的基本数据库结构。 What happens when you have to change your schema in 2 months? 如果您必须在2个月内更改架构,该怎么办?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM