xwrs
xwrs

Reputation: 1297

Generate viewmodels by LINQ

I have two lists

user.Roles
repository.Roles

and RoleViewModel

public class RoleViewModel
{
    public int RoleID { get; set; }
    public bool InRole { get; set; }
    public string Name { get; set; }

    public RoleViewModel() { }

    public RoleViewModel(Role role,bool inRole)
    {
        this.RoleID = role.RoleID;
        this.Name = role.Name;
        this.InRole = inRole;
    }
}

I need to generate any collection like List<RoleViewModel> which will be a composition of RoleViewModel items with inRole field set to true. And all other possible roles which are placed in repository.Roles collection and will be converted to RoleViewModels.

Can I use linq to generate needed list?

Thank you

Upvotes: 0

Views: 153

Answers (2)

Bryan Watts
Bryan Watts

Reputation: 45465

It seems like you want a view model for every role in the repository, and if the user is in that role, the inRole argument to be true. Please correct me if I'm wrong.

To do that, you need a left join from the repository roles to the user's roles:

from role in repository.Roles
join userRole in user.Roles on role.RoleID equals userRole.RoleID into userRoles
from userRole in userRoles.DefaultIfEmpty()
select new RoleViewModel(role, userRole != null)

This joins the set of roles in the repository to the set of roles for the user. It places the matching user roles into the userRoles sequence, then uses DefaultIfEmpty to return null for userRole if the user is not in the repository role. This way, if userRole is not null, the user is in the repository role, but if userRole is null, the user is not in the repository role.

Upvotes: 2

Becuzz
Becuzz

Reputation: 6857

Yes you can, you just need to fix your linq to call the constructor instead of assigning values to (non-existent) properties.

List<RoleViewModel> models = (from r1 in repository.Roles 
                              join r2 in user.Roles on r1.RoleID equals r2.RoleID 
                              select new RoleViewModel(r1, true)).ToList();

Upvotes: 2

Related Questions