vendredi 30 septembre 2016

What is the correct way to use Linq to reference the table you instantiate with your ViewModel as a list to generate a list of 'SelectListItems'?

I want to generate a strongly typed list of Roles in my controller along with two other lists which will be used in my view as various filters for sending an email. I'm aware I can generate the Roles list using the following:

var viewModel = new ListViewModel
        {
            Roles = db.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Id.ToString(), Text = rr.Name }).ToList(),
        };

However as I am also wanting to pass two other lists to my controller I would prefer to attain the list of roles by writing the query in the following way:

var viewModel = db.Roles

           .Select(x => new SendGroupEmailViewModel
           {
               Roles = x.Roles.Select(rr => new SelectListItem { Value = rr.Id.ToString(), Text = rr.Name }).ToList(),

           };

That way I can then attain my other two lists as part of the same query, as opposed to the previous method where they would have to be effectively separate queries to the db. Obviously what is above doesn't work, I am unable .Select on the role table by writing Roles = x.Select.

My question is, why am I unable to do this and what is the correct way to query the Roles table when writing it in a similar way to the above?

Just to be clear, the reason it has to be var viewModel = db.Roles is because for whatever reason I can't access the ID/Name Roles list otherwise due to how Identity is setup in MVC. I know there are other ways of attaining the list, I would just like to know how it can be done this specific way?

Aucun commentaire:

Enregistrer un commentaire