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

cra*_*mmy 7 .net c# linq entity-framework one-to-many

我有两个表:

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

CREATE TABLE SubThing (
        Id int,
        Name nvarchar(max),
        ThingId int (foreign key)
    );
Run Code Online (Sandbox Code Playgroud)

我想选择所有带有 SubThings 列表的事物并将它们设置为 ThingViewModel。

Thing ViewModel 很简单:

public class ThingViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<SubThingViewModel> SubThings { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

SubThingViewModel 是:

public class SubThingViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我已经选择了这样的事物记录:

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

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

oct*_*ccl 6

您可以使用SubThings 导航属性进行另一个投影:

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();
Run Code Online (Sandbox Code Playgroud)

  • 不用担心。我只是想让这篇文章在十年后变得有用。 (2认同)