[RESOLVED]select several fields from one table

how can I select the username (which is the email) and role of table Users in the ApplicationDbContext of the default MVC database.I have manages to select the emails I want to select the role of each user as well.not to forget that roles are in another
table UsersRoles.

This is what I did so far:

 public List<string> GetUsers()
            var context = new ApplicationDbContext();
            var users = context.Users.Select(m => m.Email).ToList();

            return users;
Hi, Try this

var users = context.Users.Select(m =>new {m.Email, Roles=Context.Role.where(p=>p.UserName=m.Email)}).ToList();

Hi lolo512,

To get users with roles, please refer to this code below:

db.Users.Select(u => new {Email=u.Email, Roles=u.Roles }).ToList();

Best Regards


what about the method type? It shows that there is an error concerning the method type and the rerun type.

 Cannot implicitly convert type ‘System.Collections.Generic.List<AnonymousType#1>’ to ‘System.Collections.Generic.List<string>’ 

try this

            var context = new ApplicationDbContext();
            var usersroles=(from u in context.Users
                            join r in context.Roles on u.Roles.FirstOrDefault().RoleId equals r.Id
                            select new{userroles=u.UserName+r.Name}).ToList();


I think that method return type is List<string>.

I suggest that you could create a viewmodel and return that view model.

public class ViewModel
  public string Name{get;set;}
  public ICollection<Role> Roles{get;set;}
db.Users.Select(u => new ViewModel {Name=u.Email, Roles=u.Roles }).ToList();


Leave a Reply