代码之家  ›  专栏  ›  技术社区  ›  Utku

实体框架,从多个表中获取数据并选择要显示的列

  •  1
  • Utku  · 技术社区  · 7 年前

    桌子

    My Tables

    我有三张桌子,有多对多的关系:房间、公寓和公寓。

    房间控制器

    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
    }
    

    <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>
    

    我试图用基于方法的语法获取要在表中显示的字段,但我无法显示房间所属公寓的名称。

    后果

    Result Image

    Room 表和 ApartmentName 字段 Apartment

    2 回复  |  直到 7 年前
        1
  •  2
  •   thisextendsthat    7 年前
     <td>@item.ApartmentRoom.Where(x => x.RoomID == item.Id).Select(x => x.Apartment.ApartmentName)</td>
    

    IEnumerable ,这就是为什么您的视图中会出现奇怪的输出。您想使用 Include DbSet<Apartment> 加载任何相关实体,然后使用 First 获取相关实体。Include的重载采用lambda表达式( context.Apartments.Include(a => a.Rooms) )生活在 System.Data.Entity 命名空间。

    更像:

    <td>@item.ApartmentRoom.First(x => x.RoomID == item.Id).ApartmentName</td>
    
        2
  •  1
  •   Aistis Taraskevicius    7 年前
    <td>@item.ApartmentRoom.Where(x => x.RoomID == item.Id).Select(x => x.Apartment.ApartmentName).FirstOrDefault()</td>
    

    是你想要的,所以你得到的是实际的项目,而不是查询,尽管我相信你的逻辑有点混乱。