You need to enable JavaScript to run this app. Asp.Net Core Web API使用MongoDB.Driver实现关联查询返回嵌套大学对象
优惠活动
大模型
产品
解决方案
定价
更多

Asp.Net Core Web API使用MongoDB.Driver实现关联查询返回嵌套大学对象

解决方案

步骤1:新增返回用的DTO类

你原来的Student模型中University字段是字符串类型用于存储大学ID,我们需要新增一个DTO专门用于接口返回,将University字段调整为University对象类型:

public class StudentDto
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [JsonProperty("FirstName")]
    public string FirstName { get; set; }

    [JsonProperty("LastName")]
    public string LastName { get; set; }

    [JsonProperty("University")]
    public University University { get; set; }
}

可选方案:如果不想新增DTO,可以直接修改原Student类,将原来存ID的University字段改名为UniversityId并添加[JsonIgnore]特性,再新增University类型的University属性并添加[BsonIgnore]特性,避免存储时把对象写入数据库。

步骤2:修改StudentService,增加大学集合引用

首先需要在StudentDBSettings类中新增UniversityCollectionName属性,同时在appsettings.json的配置节点下新增对应大学集合名称的配置,之后修改StudentService如下:

public class StudentService
{
    private readonly IMongoCollection<Student> _students;
    // 新增大学集合引用
    private readonly IMongoCollection<University> _universities;

    public StudentService(IStudentDBSettings settings)
    {
        var client = new MongoClient(settings.ConnectionString);
        var database = client.GetDatabase(settings.DatabaseName);

        _students = database.GetCollection<Student>(settings.StudentCollectionName);
        // 初始化大学集合
        _universities = database.GetCollection<University>(settings.UniversityCollectionName);
    }

    public List<StudentDto> Get()
    {
        // 使用LINQ关联查询,写法和EF的Join类似
        var query = from student in _students.AsQueryable()
                    join university in _universities.AsQueryable() 
                        on student.University equals university.Id into universityGroup
                    from university in universityGroup.DefaultIfEmpty()
                    select new StudentDto
                    {
                        Id = student.Id,
                        FirstName = student.FirstName,
                        LastName = student.LastName,
                        University = university
                    };
        return query.ToList();
    }
}

步骤3:修改控制器返回类型

调整StudentController的返回类型为StudentDto:

[Route("api/students")]
[ApiController]
public class StudentController : ControllerBase
{
    private readonly StudentService _studentService;

    public StudentController(StudentService studentService)
    {
        _studentService = studentService;
    }

    [HttpGet]
    public ActionResult<List<StudentDto>> Get() =>
        _studentService.Get();
}

实现原理说明

MongoDB中对应EF Core Include关联查询的是$lookup聚合操作,上述LINQ写法本质上就是生成了$lookup的聚合查询语句,实现两个集合的左外连接,和你用EF的Include效果完全一致。

内容的提问来源于stack exchange,提问作者Yopa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 15:54:00