AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

Linq get data from m to n tables?

I have 2 Tables that is m to n relationships between them. Roles, Moduls, ModulsInRoles. I get current user roles. IAnd I want to get these roles' moduls. I tried to write something. But I cant success.

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

for example; My data is like this:

Admin  Modul1
Admin  Modul2
User   Modul2
User   Modul3

And I want to get this:

Modul1
Modul2
Modul3

What is the logic? and Is there some code example or tutorial about this topic.

Thanks.

Upvotes: 0

Views: 195

Answers (2)

Shibumi
Shibumi

Reputation: 1399

To answer your question "I want to ask If Is there different way?": you could use SelectMany. I'm not sure I totally understand the structure of what you're working with, but I've guessed. Hopefully it's right.

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

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

Assuming each module returned from TblModulesInRoles is the same object referenced in each role mapping, this should work. If it's not the same object, then your module entity will probably have to be comparable by one of the standard ways.

Here's the code I used to test this locally. Obviously it's not entirely the same thing, but it demonstrates SelectMany, at least.

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 }

Upvotes: 1

Yograj Gupta
Yograj Gupta

Reputation: 9869

Try This

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

Upvotes: 1

Related Questions