c# – 如何使用Linq选择具有一对多关系的所有内容

我有两张桌子:

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

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

我想选择所有具有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; }
    }

我已经选择了像这样的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.SunThings.Select(st=>new SubThingViewModel{Id =st.Id,...}).ToList()
}).ToList();
点赞