Rest API.NET如何按需加载/(不)加载嵌套实体



我有一个带有控制器的.NET Rest API。该控制器正在应答对实体School的请求。我的数据库有许多Schools,每个School都有很多Students。

有时我希望此查询返回所有School及其Student,但有时我只想返回School的列表。

我尝试了一些方法:我在查询includeStudents上设置了一个布尔参数,该参数应该使用Entity Framework中的Include方法修改内部SQL查询以与Students表联接。

public class SchoolsController:ApiController
{
[System.Web.Http.HttpGet]
public IEnumerable<SchoolsDTO> Index(int? id = null, bool? includeStudents=null)
{
using (MyDatabase db = new MyDatabase())
{
string includeString = "";
if(includeStudents.HasValue && includeStudents.Value)
{
includeString = ".Students";
}
var schools = db.Schools.Include(includeString).AsQueryable();
if (id.HasValue)
{
schools = schools.Where(x => x.Id == id);
}

return AutoMapper.Mapper.Map<List<SchoolsDTO>>(schools.ToList());
}
}
}

但无论我是否使用Include,它总是将所有学校的Student解析并序列化为JSON。

编辑:我使用AutoMapper来处理DTO,但这些对象的DTO只是原始EF对象的相同副本。

我该如何解决这个问题?

尝试此代码

var schools = db.Schools.Where(x => id==0 || x.Id == id ).AsQueryable();
if(includeStudents != null && includeStudents)
{
schools = schools.Include(s=> s.Students);
} else schools.Students=null;

return AutoMapper.Mapper.Map<List<SchoolsDTO>>(schools.ToList());   

最新更新