我正在尝试将odata查询应用于我的automapper - 在我的efcore上下文中进行映射。在我使用$ select查询选项之前,所有内容都按预期工作。
当我尝试在我的odata-controller的请求中使用select关键字时,我得到了异常:
SerializationException:'SourceSourceInjectedQuery`2'无法使用ODataMediaTypeFormatter序列化。
我正在使用UseAsDataSource - Extension方法,因为它被推荐为here on github。
这是我的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>()
);
}
}
这是我的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; }
}
这是我对automapper的mappingprofile:
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>();
}
}
我需要一些特定的映射才能执行此操作吗?
我发现我在startup.cs中配置odataservice时出错了
private static IEdmModel GetEdmModel() {
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Student>("Students");
builder.EntitySet<Course>("Courses");
return builder.GetEdmModel();
}
我把我的实体而不是我的ViewModel放在那里。这是固定代码:
private static IEdmModel GetEdmModel() {
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<StudentVM>("Students");
builder.EntitySet<CourseVM>("Courses");
return builder.GetEdmModel();
}
现在它按预期工作了