[英]Linq get data from m to n tables?
我有2個表,它們之間有m到n個關系。 角色,模塊,ModulsInRoles。 我獲得了當前的用戶角色。 我希望得到這些角色的模塊。 我試着寫點東西。 但我不能成功。
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
邏輯是什么? 是否有關於此主題的一些代碼示例或教程。
謝謝。
嘗試這個
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);
}
}
回答你的問題“我想問一下,如果有不同的方式嗎?” :你可以使用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 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.