I am trying to apply the odata query to my automapper - mappings at my efcore context. Everything works as expected until I use the $select query option.

When I try to use the select keyword in the request to my odata - controller, I get the exception:

SerializationException: 'SourceSourceInjectedQuery`2' cannot be serialized using the ODataMediaTypeFormatter.

I am using the UseAsDataSource - Extension method because it was recommended here on github.

This is my oDataController:

public class StudentsController : ODataController {
    private readonly SchoolContext schoolContext;

    public StudentsController(SchoolContext schoolContext) {
        this.schoolContext = schoolContext;
    }
    [EnableQuery]
    public IActionResult Get() {

        return Ok(
            schoolContext
            .Students
            .UseAsDataSource()
            .For<StudentVM>()
        );
    }
}

This is my Entity for EFCore:

public class Student {
    public int ID { get; set; }
    public string LastName { get; set; }
    public string FirstMidName { get; set; }
    public DateTime EnrollmentDate { get; set; }

    public ICollection<Enrollment> Enrollments { get; set; }
}

And this is my mappingprofile for automapper:

public class StudentVM {
    public int ID { get; set; }
    public string  LastName { get; set; }
    public string FirstMidName { get; set; }
}

public class StudentProfile : Profile {
    public StudentProfile() {
        CreateMap<Student, StudentVM>();
    }
}

Do I need some specific mapping to do this?

1 Answers

0
Weissvonnix On Best Solutions

I figured out I had a mistake in my configuration of the odataservice inside my startup.cs

    private static IEdmModel GetEdmModel() {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<Student>("Students");
        builder.EntitySet<Course>("Courses");
        return builder.GetEdmModel();
    }

I put my Entities instead of my ViewModels there. This is the fixed code:

    private static IEdmModel GetEdmModel() {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<StudentVM>("Students");
        builder.EntitySet<CourseVM>("Courses");
        return builder.GetEdmModel();
    }

Now it's working as expected