Linq to Entities查询 - 查找具有相同字段值的所有记录

时间:2012-08-04 10:17:12

标签: linq-to-entities

我正在使用以下Linq to Entities Query,在唯一字段上查询一次,然后查找与单独(外键)属性匹配的所有记录:

public IEnumerable<User> getUsersInSameCentreAs(String userName)
{
    int? studyCentreId = (from u in _db.Users
                         where u.UserName == userName
                         select u.StudyCentreID).FirstOrDefault();
    return (from u in _db.Users
            where u.StudyCentreID == studyCentreId
            select u).ToList();
    }

必须有一个干净/单一的查询,它只会查询一次数据库以获得相同的结果,但我对实体的linq知识让我失望 - 任何人都可以看到更好的解决方案。谢谢。

1 个答案:

答案 0 :(得分:1)

子查询将解决这个问题:

return (from u in _db.Users
        where u.StudyCentreID == (from u2 in _db.Users
                     where u2.UserName == userName
                     select u2.StudyCentreID).FirstOrDefault();
        select u).ToList();