EF核心:只返回两个级别的相关日期

问题描述 投票:0回答:1

我有一个简单的设置,我试图获得基于父实体的二级子实体。

public class Country {
  public string Name {get;set;}
  public List<State> States {get;set;}
}

public class State {
 public string Name {get;set;}
 public Country Country {get;set;}
 public List<City> Cities {get;set;}
}

public class City {
 public string Name {get;set;}
 public State State {get;set;}
}

我如何仅检索具有Country.Name ==“Japan”父级的城市(基本上忽略所有其他信息)?

我知道ThenInclude:

dbContext.Countries
.Include(o => o.States}
.ThenInclude(x => x.Cities)
.Where(o => o.Name.Equals("Japan"))
.ToList();

然后我必须提取每个城市列表并将其组合到仅包含列表的新列表中(我认为这不是优雅的方式)。

asp.net entity-framework entity-framework-core
1个回答
0
投票

发现最简单的方法是从反向查看它。

 await dbContext.Cities
       .Where(o => o.State.Country.Name.Equals("Japan"))
       .ToListAsync();

这将仅返回具有名称为Japan的祖父母的城市列表。

© www.soinside.com 2019 - 2024. All rights reserved.