。在哪里。选择,如何只选择匹配where子句的记录: -

时间:2013-11-16 19:36:48

标签: c# linq entity-framework

我有以下两个陈述: -

var isadminByuser = tms.SecurityRoles.Where(a => a.Name.ToLower() == "administrator")
                                     .Select(a=>a.SecurityRoleUsers.Where(a2 => a2.UserName.ToLower() == user.ToLower()));

if (isadminByuser.Count() >= 1) { return true;}

&安培;

var adminByGroup = tms.SecurityRoles.Where(a => a.Name == "Administrator")
                      .SingleOrDefault().Groups
                      .Select(a2 => a2.TMSUserGroups
                                      .Where(a3 => a3.UserName.ToLower() == user.ToLower()));

bool isadminByGroup = adminByGroup.Count() >= 1;

第一个var isadminByuser将始终包含元素(始终为> = 1),即使where子句a3.UserName.ToLower() == user.ToLower()))false,而另一个var也有计数零是where子句(a3.UserName.ToLower() == user.ToLower()))是false。那么为什么第一个var永远不会有零?

由于

2 个答案:

答案 0 :(得分:1)

问题的答案是您在选择时选择IQueryable<SecurityRoleUsers>     a.SecurityRoleUsers.Where(a2 => a2.UserName.ToLower() == user.ToLower())

可能有也可能没有0,但包含查询将为匹配IQueryables的每个SecurityRole返回其中一个Name = "administrator",因此计数将始终为1 +如果至少有一个匹配SecurityRole

更新

// first get SecurityRoles
bool isadminByuser = tms.SecurityRoles.Where(a => a.Name.ToLower() == "administrator")
    // now you're only interested in the related SecurityRoleUsers
    .SelectMany( a => a.SecurityRoleUsers )
    // now check if any of the SecurityRoleUsers meet your criteria
    .Any( sru => sru.UserName.ToLower() == user.ToLower() );

答案 1 :(得分:0)

您能否观察到ms-sql-profiler

的SQL查询差异
tms.SecurityRoles.Where(a => a.Name.ToLower() == "administrator")
                                     .Select(a=>a.SecurityRoleUsers.Where(a2 => a2.UserName.ToLower() == user.ToLower()));

***

tms.SecurityRoles.Select(a=>a.SecurityRoleUsers.Where(a2 => a2.UserName.ToLower() == user.ToLower())).Where(a => a.Name.ToLower() == "administrator");