Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Child Object with LINQ

I'm learning many-to-many joint tables within EF Core and LINQ. I have the following model:

    public class ProjectManager
    {
        public int ProjectID { get; set; }
        public Project Project { get; set; }

        public string AppUserID { get; set; }
        public AppUser AppUser { get; set; }
    }

I have the following ViewModel:

    public class DeleteUserFromProjectViewModel
    {
        public IQueryable<AppUser> Users { get; set; }
        public PagingInfo PagingInfo { get; set; }
    }

In my controller, I try to populate the Users for my ViewModel:

                DeleteUserFromProjectViewModel model = new DeleteUserFromProjectViewModel
                {
                    //HOW DO I RETURN JUST THE APPUSERS FROM THE PROJECT MANAGER OBJECT?
                    //Users = repository.ProjectManagers.Any(p => p.ProjectID == projectId).Select;

                    PagingInfo = new PagingInfo
                    {
                        CurrentPage = page,
                        ItemsPerPage = PageSize,
                        TotalItems = proj.ProjectManagers.Count()
                    }

                };

I've tried the kludge

                List<AppUser> userList = new List<AppUser>();
                foreach(ProjectManager pm in proj.ProjectManagers)
                {
                    //this gives error that cannot convert string userId to char??
                    foreach (string userId in pm.AppUserID)
                    {
                        AppUser newUser = await userManager.FindByIdAsync(userId);
                        userList.Add(newUser);
                    }
                }
like image 722
coolhand Avatar asked Dec 07 '25 19:12

coolhand


1 Answers

Because of your pm.AppUserID already is a string value, if you use foreach on it you will iterator string value then you will get char

From your comment, you seem like can use linq Select.

List<AppUser> userList = proj.ProjectManagers.Select(x=>x.AppUser).ToList();
like image 122
D-Shih Avatar answered Dec 09 '25 08:12

D-Shih