2012-07-18 21 views
0

我有2個表格,它們之間是m到n的關係。角色,模塊,ModulsInRoles。我獲得當前的用戶角色。我想要得到這些角色的模型。我試圖寫點東西。但我不能成功。Linq從m數據表中獲取數據?

string[] roller = System.Web.Security.Roles.GetRolesForUser(); 

IEnumerable<TblModuller> moduller = null; 
IEnumerable<TblModulsInRoles> moduls_in_roles = null; 

foreach (var rol in roller) 
{ 
    moduls_in_roles = entity.TblModulsInRoles.Where(x => x.Roles.RoleName == rol); 
    foreach(var modul in moduls_in_roles) 
    { 
     //I dont know What should I write or this code is correct. 
    } 
} 

例如;我的數據是這樣的:

Admin Modul1 
Admin Modul2 
User Modul2 
User Modul3 

而且我要得到這個:

Modul1 
Modul2 
Modul3 

這是什麼邏輯?有沒有關於這個主題的代碼示例或教程。

謝謝。

回答

1

嘗試這個

var modullerList = new List< TblModuller>(); 

foreach (var rol in roller) 
{ 
    moduls_in_roles = entity.TblModulsInRoles.Where(x => x.Roles.RoleName == rol); 
    foreach(var modul in moduls_in_roles) 
    { 
     if(!modullerList .Contains(modul)) 
      modullerList .Add(modul); 
    } 
} 
+0

謝謝。它的工作原理,但我想問如果有不同的方式? – 2012-07-18 13:31:28

+0

var modullerList = entity.TblModulsInRoles.Where(roller.Contains(x.Roles.RoleName));這也會返回相同的結果。 – 2012-07-18 13:38:23

1

要回答你的問題「我想問如果有不同的方式?」:您可以使用SelectMany。我不確定我完全理解你正在使用的結構,但我猜到了。希望是對的。

string[] roles = System.Web.Security.Roles.GetRolesForUser(); 

var modules = roles 
    .SelectMany(r => 
     entity.TblModulsInRoles.Where(m => m.Roles.RoleName == r) 
    ) 
    .Distinct(); 

假設從TblModulesInRoles返回的每個模塊是在各個角色映射引用的相同的對象,這應該工作。如果它不是同一個對象,那麼你的模塊實體可能必須通過其中一種標準方法進行比較。

這裏是我用來在本地測試的代碼。顯然這不完全是一回事,但它至少證明了SelectMany

public class Module 
{ 
    public Module(string name) 
    { 
     Name = name; 
    } 

    public string Name { get; private set; } 
} 

Module one = new Module("one"); 
Module two = new Module("two"); 
Module three = new Module("three"); 

Dictionary<string, List<Module>> dict = new Dictionary<string, List<Module>> 
{ 
    {"cow", new List<Module> { one, two }}, 
    {"chicken", new List<Module> { one }}, 
    {"pig", new List<Module> { two }} 
}; 

string[] roles = new string[] { "cow", "chicken", "pig" }; 

var result = roles.SelectMany(r => dict[r]).Distinct(); 

Console.WriteLine(result); 

// { one, two }