EF Core return specific columns from child tables

c# entity-framework-core linq

Question

I don't want to use .include to get the entire child tables. I just need select columns.

public class ProjectTypeDTO {
    public string Type { get; set; }
}

public class CourseDTO {
    public string CourseCode { get; set; }
    public string CourseTitle { get; set; }
}

public class ProjectDTO {
    public int Id { get; set; }
    public ProjectTypeDTO ProjectType { get; set; }
    public CourseDTO Course { get; set; }
    public string StartTerm { get; set; }
    public DateTime SignOff { get; set; }
    public DateTime StartDateTime { get; set; }
}

[HttpGet("getallprojects")]
public IActionResult GetAllProjects()
{
    var projects = _context.Projects
          .Select(p => new ProjectDTO
           {
               Id = p.Id,
               ProjectType = { Type = p.ProjectType.Type },
               Course = { CourseCode = p.Course.CourseCode, CourseTitle = p.Course.CourseTitle },
               StartTerm = p.StartTerm,
               SignOff = p.SignOff,
               StartDateTime = p.StartDateTime,
               }).ToList();

    return Ok(projects);
}

This is throwing a "NotImplementedException: The method or operation is not implemented." error.

I've tested it as an anonymous function and it works.

var projects = _context.Projects
    .Select(p => new
    {
        p.Id,
        p.ProjectType.Type,
        p.SignOff,
        p.StartDateTime,
        p.Course.CourseCode,
        p.Course.CourseTitle,
        p.StartTerm
     }).ToList();

An anonymous type won't work for my app, since I need to be able to make changes to this data before it gets returned.

Based on other examples I've seen here and other sites, this looks correct. Could it be a bug?

1
0
6/19/2018 6:14:24 PM

Popular Answer

I haven't seen that syntax for sub-objects before. eg:

ProjectType = { Type = p.ProjectType.Type }

I believe that should be:

ProjectType = new ProjectTypeDTO{ Type = p.ProjectType.Type }
2
6/19/2018 6:18:14 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow