Context: I am making an e-learning app in ASP.NET with MongoDB
I have a Course collection
public class CourseDTO : DTOBase
{
[BsonId] public ObjectId Id { get; init; }
public required string Name { get; init; }
public required string Description { get; init; }
public required string ImageUrl { get; init; }
public required ObjectId Teacher { get; init; }
public ObjectId[] StudentIds { get; init; } = [];
}
and a User collection
public class UserDTO : DTOBase
{
[BsonId] public ObjectId Id { get; init; }
public required string Username { get; init; }
public required string PasswordHash { get; init; }
public required string PasswordSalt { get; init; }
}
I want to implement a method to fetch a Course from its ObjectId
and map the StudentIds to the related Users
If possible I would prefer to do it in a single request, and keep the query type safe
So far I managed to fetch the Course with the “easy” fields, I am just missing the Students
public async Task<CourseModel> Get(ObjectId id) {
var query = from c in repo.Courses.AsQueryable()
where c.Id == id
join t in repo.Users.AsQueryable() on c.Teacher equals t.Id
select new CourseModel {
Id = c.Id.ToString(),
Name = c.Name,
Description = c.Description,
ImageUrl = c.ImageUrl,
Teacher = new UserModel {
Id = t.Id.ToString(),
Username = t.Username
}
// todo: add students
};
var course = await query.FirstOrDefaultAsync();
if (course == null) throw new NotFoundException("Course not found");
return course;
}
public class UserModel
{
public required string Id { get; init; }
public required string Username { get; init; }
}
public class CourseModel
{
public required string Id { get; init; }
public required string Name { get; init; }
public required string Description { get; init; }
public required string ImageUrl { get; init; }
public required UserModel Teacher { get; init; }
public UserModel[] Students { get; init; } = [];
}
I could get the Students in another query easily but it would be more efficient to do everything in one query
Thomas Renon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.