Linq从m到n表获取数据?

时间:2012-07-18 13:17:31

标签: c# linq relational-database

我有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

逻辑是什么?是否有关于此主题的一些代码示例或教程。

感谢。

2 个答案:

答案 0 :(得分: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);
     }
}

答案 1 :(得分: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 }