Nikita Goncharuk
Nikita Goncharuk

Reputation: 815

Entity Framework Core: Request for Composite Table (Composite Key)

I. Hi! I create a composite key ProjectSubProject for my models: Project and SubProject. I have a problem with create GetAllProjects request, i want to get a

IGrouping<Project, IEnumerable<SubProject>> or IDictionary structure, but i get IGrouping<Project, IEnumerable<GetAllProjectsViewModel>>

Here is my request:

return _context.ProjectSubProjects
                .Include(ps => ps.Project)
                .Include(ps => ps.SubProject)
                .Select(ps => new GetAllProjectsViewModel
                {
                    Project = ps.Project,
                    SubProject = ps.SubProject,
                })
                .GroupBy(ps => ps.Project);

Project.cs:

public class Project
    {
        // PK
        public int Id { get; set; }

        public string ProjectName { get; set; }

    }

SubProject.cs:

public class SubProject
    {
        // PK
        public int Id { get; set; }

        public string SubProjectName { get; set; }
    }

ProjectSubProject.cs

public class ProjectSubProject
    {
        // PK
        public int ProjectId { get; set; }
        public Project Project { get; set; }

        // PK
        public int SubProjectId { get; set; }
        public SubProject SubProject { get; set; }
    }

enter image description here

Upvotes: 1

Views: 180

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205729

To get IEnumerable<IGrouping<Project, IEnumerable<SubProject>>> from your model, no Include or Select is needed. You can simply use the GroupBy method overload which allows you to pass element selector:

return _context.ProjectSubProjects
    .GroupBy(ps => ps.Project, ps => ps.SubProject);

Update: In order to include the project information in the Json representation, you could project the result to enumerable of some special or anonymous type having Project and SubProjects properties. Something like this:

return _context.ProjectSubProjects
    .GroupBy(ps => ps.Project, ps => ps.SubProject)
    .Select(g => new { Project = g.Key, SubProjects = g });

Upvotes: 2

Related Questions