如何使用Linq选择具有一对多关系的所有

时间:2017-04-28 15:20:11

标签: c# .net entity-framework linq one-to-many

我有两张桌子:

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

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

我想选择包含SubThings列表的所有Things并将它们设置为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; }
    }

我已经选择了像这样的东西记录:

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

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

1 个答案:

答案 0 :(得分:1)

您可以使用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();