c# - 使用 LINQ 返回子对象

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

我正在学习 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; }
    }

我有以下 View 模型:

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

在我的 Controller 中,我尝试为我的 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);
                    }
                }

最佳答案

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

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

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

关于c# - 使用 LINQ 返回子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348138/

相关文章:

c# - DbContext.ChangeTracker.HasChanges 非常慢

.net - Entity Framework 4 - 代码优先和存储过程

用于获取与 ID 数组的所有项目匹配的项目的 LINQ 查询

c# - 尽管使用 *include* 仍出现 ObjectDisposeException

c# - LINQ to SQL 分组依据与 take

c# - 如何在没有 AAD 访问权限的 Microsoft 团队聊天机器人中实现用户身份验证?

c# - 使用具有包含在 HTML 中的外部 CSS 类的 PdfSharp 从 HTML 片段创建 PDF

c# - 解析bool的简单方法?在一行中

c# - 如何减少行数的边距大小

entity-framework - 错误 : The type 'TEntity' must be a reference type