首页 > 解决方案 > 如何在 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

标签: asp.netasp.net-coreasp.net-web-api

解决方案


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)
                            });

推荐阅读