Search code examples
c#asp.net-mvcentity-frameworkmany-to-manyrepository-pattern

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.

Tables

My Tables

I have three tables with many-to-many relationship: Room, ApartmentRoom and Apartment.

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>

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

Result Image

In the view, I want to list the all fields of Room table and ApartmentName field of Apartment table.


Solution

  •  <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. 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. The overload of Include taking a lambda expression ( context.Apartments.Include(a => a.Rooms) ) lives in the System.Data.Entity namespace.

    More like:

    <td>@item.ApartmentRoom.First(x => x.RoomID == item.Id).ApartmentName</td>