2010-10-22 47 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