2010-10-22 46 views
1

我有一种感觉,还支持使用连接可以使这种清洁如何使用连接使此查询更清洁?

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; 
     } 
    } 
} 

回答

1

您应该能够使用导航属性跟随关系,而不是使用主键(实体框架将加入场景,你的身后)

如果你有(和需要)UserInRoles因为有上结合表定义的其他属性,可以使用:

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

否则确保NM relatio n被映射为这样,并且不映射联结表。然后,你可以使用:

return (from u in cts.Users 
     from r in u.Roles 
     select r.roleName).ToArray(); 
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; 

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

+0

如果您发布代码或XML,请**在文本编辑器中高亮显示这些行,然后单击编辑器工具栏上的“代码”按钮(101 010)以很好的格式和语法突出显示它! – 2010-10-22 21:13:32