从多个表中获取数据时,我非常困惑。我在我的项目中使用MVVM和数据库第一种方法。实体框架,从多个表中获取数据并选择要显示的列
表
我有三个表许多一对多的关系:客房,ApartmentRoom和公寓。
RoomController
public class ApartmentController : Controller
{
private readonly IApartmentRepository _apartmentRepository;
public ApartmentController(IApartmentRepository apartmentRepository)
{
_apartmentRepository = apartmentRepository;
}
//...codes
[HttpGet]
public ActionResult List()
{
var apartmentList = _apartmentRepository.GetAll().ToList();
return View(apartmentList);
}
//...codes
}
List.cshtml
<div class="dataTables_wrapper">
<table class="table table-bordered table-striped" id="dataTable">
<thead>
<tr>
<th>Id</th>
<th>Door Number</th>
<th>Floor Number</th>
<th>Capacity</th>
<th>Fullness</th>
<th>Apartment Name</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.ToList())
{
<tr>
<td>@item.Id</td>
<td>@item.DoorNumber</td>
<td>@item.FloorNumber</td>
<td>@item.Capacity</td>
<td>@item.Fullness</td>
<td>@item.ApartmentRoom.Where(x => x.RoomID == item.Id).Select(x => x.Apartment.ApartmentName)</td>
<td>
@Html.ActionLink("Düzenle", "Edit", new { id = item.Id })
@Html.ActionLink("Sil", "Delete", new { id = item.Id })
</td>
</tr>
}
</tbody>
</table>
我试图让我想在此表以显示与基于方法的语法领域,但我无法显示房间所属公寓的名称。
结果
在视图中,我想列出Room
表和Apartment
表ApartmentName
领域的各个领域。
您可能需要在dbcontext配置中禁用延迟加载或使用Include方法获取子表记录。 –