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

情到浓时终转凉″ 提交于 2021-02-18 12:57:32

问题


I have two tables:

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

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

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

The Thing ViewModel is simple:

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

The SubThingViewModel is:

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

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();

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


回答1:


You could do another projection using 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();


来源:https://stackoverflow.com/questions/43683677/how-to-select-all-with-a-one-to-many-relationship-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!