如何使用join来使这个查询更干净?

时间:2010-10-22 20:08:36

标签: linq entity-framework

我觉得使用连接可以使这个更清洁

public override string[] GetRolesForUser(string username)
{
   using (TemplateEntities ctx = new TemplateEntities())
   {
      using (TransactionScope tran = new TransactionScope())
      {
         int userId = (from u in ctx.Users
                       where u.UserName == username
                       select u.UserId).Single();
         int[] roleIds = (from ur in ctx.UserInRoles
                          where ur.UserId == userId
                          select ur.RoleId).ToArray();
         string[] roleNames = (from r in ctx.Roles
                               where roleIds.Contains(r.RoleId)
                               select r.RoleName).ToArray();
         tran.Complete();
         return roleNames;
      }
   }
}

2 个答案:

答案 0 :(得分:1)

您应该能够使用导航属性来关注关系,而不是使用主键(实体框架将在幕后为您加入)

如果您有(并且需要)UserInRoles,因为在联结表上定义了其他属性,您可以使用:

return (from u in cts.Users
        from ur in u.UserInRoles
        from r in ur.Roles
        select r.roleName).ToArray();

否则确保N-M关系如此映射,并且不映射联结表。然后你可以使用:

return (from u in cts.Users
        from r in u.Roles
        select r.roleName).ToArray();

答案 1 :(得分:0)

我不是c#家伙,但基本上你想做

select u.userId, ur.roleId, r.roleName 
from Users u, UserInRoles ur, Roles r 
where u.userId = ? and ur.userId = u.userId and r.roleId = ur.roleId; 

如果您选择嵌套查询,也可以使用in语法。 ie:where user_id in(从UserInRoles中选择userId)