asp.net - 如何在 ASP.NET Core 3.1 API 中显示指定的列数据
问题描述
这是我的代码:
public string LoadAllWeeks(int course_id)
{
var dbSnapShot = db.CourseWeeks
.Include(cw=>cw.WeekQuestions)
.ThenInclude(cq => cq.Qn)
.ThenInclude(q => q.Answers)
.Where(c => c.CourseId == course_id);
var serializedItem = JsonConvert.SerializeObject(dbSnapShot, Formatting.Indented,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return serializedItem;
}
此代码返回每个表的完整数据,但我希望它只返回每个表的第二列数据。我怎样才能做到这一点?这些是我得到的 json 图像。1
解决方案
1.您可以创建一个包含指定列的视图模型:
型号(仅举例):
public class People
{
public int id { get; set; }
public string peepleName { get; set; }
public List<Cats> Cats { get; set; }
}
public class Cats
{
public int id { get; set; }
public string catName { get; set; }
}
视图模型:
public class ViewModel
{
public string peepleName { get; set; }
public string catName { get; set; }
}
显示指定列:
var dbSnapShot = _context.People.Include(a => a.Cats).Where(a => a.id == 1)
.Select(a => new ViewModel
{
peepleName = a.peepleName,
catName = a.Cats.Select(a=>a.catName).ToList()
});
2.您也可以使用匿名类型,如下所示:
var dbSnapShot = _context.People.Include(a => a.Cats).Where(a => a.id == 1)
.Select(a => new
{
Name =a.peepleName,
CName = a.Cats.Select(a=>a.catName)
});
推荐阅读
- python - 哪种过滤器更好更快
- java-native-interface - 调用打包在 jar 文件中的本机方法时出现 UnsatisfiedLinkError
- swift - Apple 地图显示自定义引脚详细信息和始终打开模式
- php - 在 MySQL 准备语句中将 2+ 数组绑定为参数的解决方案?
- vba - 自动将个别成员的姓名和金额插入消息正文,并以短信形式发送到相应号码
- c# - 如何让 WPF DataGrid 定制错误样式适用于值转换器错误?
- c++ - 使用 strtok 函数对给定字符串拆分字符串不适用于字符串
- python - 捐赠系统循环,系统将再次询问,直到达到固定目标金额
- mysql - 如何使用 DBEdit 自动完成多个表格
- javascript - JS 使用 Kotlin 和 Duktape 在 Android 中传播语法