如何从具有两个1对多关系的3个表中读取数据

时间:2018-01-19 18:32:04

标签: entity-framework linq asp.net-core-mvc

我有3张桌子

public class Student
{
    public int id;
    public string StudentName
    public int TownId
    public Town Town
}

public class City
{
    public int id;
    public string CityName
    public int CountryId
    public Country Country
    public Icollection<Student>S tudent
}

public class Country
{
    public int id;
    public string CountryName
    public Icollection<City> Cities
}

我想点击县内索引页面上的国家/地区的详细信息链接,通过控制器获取2个循环进入详细信息页面。 第一个将显示该国家的所有城市,第二个将以表格的形式显示该镇的所有学生。

的内容
| City Name| |Students|<br>
|London    |  |John Doe ,John Doe2|<br>

我使用以下代码连接Details控制器

中的表
  public IActionResult Details(int? ID) {

            if (ID == null)
                return NotFound();

            var country = DB.Country
                .Where (d => d.Id == ID )
                .Include( d => d.City )
                .ThenInclude( d => d.Student )
                .FirstOrDefault();

            return View( country );    
        }

如果当我将模型发送到csshtml文件时,它会加载Country和City部分 它还会在City中加载Student导航器,但我无法调出任何Student类属性。

我做错了什么?我如何调用学生属性

1 个答案:

答案 0 :(得分:1)

因为Student是一个集合,你应该迭代它。它看起来像那样;

var country = DB.Country.Where(d => d.Id == ID).Include(d => d.City)
             .ThenInclude(d=>d.Student).FirstOrDefault();

var students = country.Select(x => x.City.Student);
foreach(var student in students)
{
   //student.StudentName
}
相关问题