如何使用 Linq Select 全部具有一对多关系

How to Select All with a One to Many Relationship Using Linq

我有两个表:

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

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

我想 select 所有具有 SubThings 列表的事物,并将它们设置为 ThingViewModel。

Thing ViewModel 很简单:

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

SubThingViewModel 是:

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

我已经 select Thing 这样记录了:

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

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

您可以使用 SubThings navigation property:

进行另一个投影
things = _context.Things.OrderBy(b => b.Name)
.Select(b => new ThingViewModel
{
     Id = b.Id,
     Name = b.Name,
     SubThings =b.SubThings.Select(st=>new SubThingViewModel{Id =st.Id,...}).ToList()
}).ToList();