【问题标题】:Return Child Object with LINQ使用 LINQ 返回子对象
【发布时间】:2023-03-24 16:10:01
【问题描述】:

我正在学习 EF Core 和 LINQ 中的多对多联合表。我有以下型号:

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

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

我有以下 ViewModel:

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

在我的控制器中,我尝试为我的 ViewModel 填充 Users

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

                };

我已经试过了

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

【问题讨论】:

    标签: c# entity-framework linq asp.net-core


    【解决方案1】:

    因为你的pm.AppUserID 已经是一个字符串值,如果你在它上面使用foreach 你会迭代字符串值然后你会得到char

    从您的评论来看,您似乎可以使用 linq Select

    List<AppUser> userList = proj.ProjectManagers.Select(x=>x.AppUser).ToList();
    

    【讨论】:

    • 我认为这一定很接近,但我收到了错误Cannot implicitly convert the type System.Collections.Generic.List&lt;System.Threading.Tasks.Task&lt;AppUser&gt;&gt; to System.Linq.IQueryable&lt;AppUser&gt;
    • 我还没有让FindByIdAsync 与我的ProjectManager 班级一起工作。是否可以拨打repository.ProjectManagers.Where(...) 电话?我已经用 Projectmanagers 数据设置了我的 dbContext
    • 或者你可以试试我的编辑答案使用repository.ProjectManagers.Select(x=&gt;x.AppUser).ToList()
    • 没问题很高兴帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 2023-03-17
    相关资源
    最近更新 更多