当我尝试通过 AutoMapper 将数据转换为另一种类型时,我得到以下函数:
System.InvalidOperationException: The LINQ expression 'DbSet<UserMaterial>()
System.InvalidOperationException
The LINQ expression 'DbSet<UserMaterial>()
.Where(cm => cm.UserId == u.Outer.Outer.UserId)
.Where(cm => DbSet<CourseMaterial>()
.Where(courseMaterial => courseMaterial.CourseId == u.Outer.Outer.CourseId)
.Select(courseMaterial => courseMaterial.MaterialId)
.Any(materialId => materialId == cm.MaterialId)
)
.Select(um => um.Grade)
.OrderByDescending(grade => grade)
.LastOrDefault(0)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
代码(IPractiflyContext为接口(原类型为PractiflyContext(DbContext)):
public class PractiFlyProfile : Profile
{
private readonly PractiFlyContext _context;
public PractiFlyProfile(IPractiflyContext context)
{
_context = context;
CreateProjection<UserCourse, UserCourseStatusDto>()
.ForMember(e => e.CourseId, par => par.MapFrom(e => e.CourseId))
.ForMember(e => e.Language, par => par.MapFrom(e => e.Course.Language.Code))
// TODO: можливо оцінки беруться із тем та з матеріалів
.ForMember(
e => e.GradeAverage,
par => par.MapFrom(
e => (
(float)_context
.Set<UserMaterial>()
.Where(cm => cm.UserId == e.UserId)
.Where(cm => _context.Set<CourseMaterial>()
.Where(courseMaterial => courseMaterial.CourseId == e.CourseId)
.Select(courseMaterial => courseMaterial.MaterialId)
.Any(materialId => materialId == cm.MaterialId))
.Select(um => um.Grade)
.DefaultIfEmpty()
.Average()
)
)
)
.ForMember(
e => e.Grade,
par => par.MapFrom(
e => _context
.UserMaterials
.Where(cm => cm.UserId == e.UserId)
.Where(cm => _context.CourseMaterials
.Where(courseMaterial => courseMaterial.CourseId == e.CourseId)
.Select(courseMaterial => courseMaterial.MaterialId)
.Any(materialId => materialId == cm.MaterialId)
)
.Select(um => um.Grade)
.OrderByDescending(grade => grade)
.LastOrDefault(0)
)
)
.ForMember(
e => e.Description,
par => par.MapFrom(e => e.Course.Description)
)
.ForMember(
e => e.Name,
e => e.MapFrom(e => e.Course.Name)
)
.ForMember(
e => e.Language,
e => e.MapFrom(e => e.Course.Language.Code)
)
.ForMember(
e => e.CourseId,
e => e.MapFrom(e => e.CourseId)
);
}
}
我想尝试转换为另一种数据类型,但我一直出错。我认为原因在于上下文