[英]Entity Framework, getting data from multiple tables and choosing columns to display
I am very confused while getting data from multiple tables. 从多个表中获取数据时我非常困惑。 I am using MVVM and Database first approaches on my project.
我在我的项目中使用MVVM和数据库第一种方法。
Tables 表
I have three tables with many-to-many relationship: Room, ApartmentRoom and Apartment. 我有三张桌子,有多对多关系:Room,ApartmentRoom和Apartment。
RoomController 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 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>
I have tried to get the fields I want to show in the table with a method based syntax, but I couldn't show the names of the apartments which rooms belong to. 我试图通过基于方法的语法获取我想要在表中显示的字段,但我无法显示房间所属的公寓的名称。
Result 结果
In the view, I want to list the all fields of Room
table and ApartmentName
field of Apartment
table. 在视图中,我想列出
Apartment
表的Room
表和ApartmentName
字段的所有字段。
<td>@item.ApartmentRoom.Where(x => x.RoomID == item.Id).Select(x => x.Apartment.ApartmentName)</td>
^^That just calls ToString on an IEnumerable
, which is why you're getting that strange output in your view. ^^只是在
IEnumerable
上调用ToString,这就是为什么你在视图中得到那个奇怪的输出。 You want to use the Include
method on your DbSet<Apartment>
to load any related entities and then use First
to get the related entity in question. 您希望在
DbSet<Apartment>
上使用Include
方法加载任何相关实体,然后使用First
来获取相关实体。 The overload of Include taking a lambda expression ( context.Apartments.Include(a => a.Rooms)
) lives in the System.Data.Entity
namespace. Include采用lambda表达式(
context.Apartments.Include(a => a.Rooms)
)的context.Apartments.Include(a => a.Rooms)
位于System.Data.Entity
命名空间中。
More like: 更像:
<td>@item.ApartmentRoom.First(x => x.RoomID == item.Id).ApartmentName</td>
<td>@item.ApartmentRoom.Where(x => x.RoomID == item.Id).Select(x => x.Apartment.ApartmentName).FirstOrDefault()</td>
是你所追求的,所以你得到实际的项而不是查询,但我相信你的逻辑有点破碎。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.