如何使用Linq以一对多关系选择全部 [英] How to Select All with a One to Many Relationship Using Linq

查看:26
本文介绍了如何使用Linq以一对多关系选择全部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表:

CREATE TABLE Thing (
    Id int,
    Name nvarchar(max)
);

CREATE TABLE SubThing (
        Id int,
        Name nvarchar(max),
        ThingId int (foreign key)
    );

我想选择带有SubThings列表的所有Things,并将它们设置为ThingViewModel.

I want to select all Things with a listing of SubThings and set them to a ThingViewModel.

Thing ViewModel很简单:

The Thing ViewModel is simple:

public class ThingViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<SubThingViewModel> SubThings { get; set; }
}

SubThingViewModel是:

The SubThingViewModel is:

public class SubThingViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

我已经选择了Thing记录,如下所示:

I already select the Thing records like this:

List<ThingViewModel> things = null;
things = _context.Things.OrderBy(b => b.Name)
    .Select(b => new ThingViewModel
    {
         Id = b.Id,
         Name = b.Name
    }).ToList();

如何将SubThings添加到查询和ViewModel中?

How would I add the SubThings to the query and ViewModel?

推荐答案

您可以使用 SubThings 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆