【问题标题】:How to show specified column data in an ASP.NET Core 3.1 API如何在 ASP.NET Core 3.1 API 中显示指定的列数据
【发布时间】:2021-04-06 06:25:09
【问题描述】:

这是我的代码:

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.NET Core 3.1 项目,我们只是在 sql server 中创建了表,我们的 dbcontext 和所有模型都是由 EF Core 自动创建的。那么我们可以在哪里为此创建 UserViewModel。
  • 下面我提供了两种简单的方法。你的模型不共享,所以我只是提供一个简单的demo。

标签: asp.net asp.net-core asp.net-web-api


【解决方案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)
                            });

【讨论】:

    猜你喜欢
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多