如何使用Linq以一对多关系选择全部

如何使用Linq以一对多关系选择全部

本文介绍了如何使用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 导航属性:

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

这篇关于如何使用Linq以一对多关系选择全部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:57