0

I am looking at moving a website from ASP.NET Web Pages to MVC. I need to understand how i do mutliple joins using entity framework.

I currently have 3 database tables with a model for each.

  • Property
  • Rooms
  • RoomType

The code below gets all the info from the rooms table for each property, but it just gives me a RoomTypeID from the Rooms table. What I need is to get the RoomType from the RoomType table using that ID.

@model manage.stayinflorida.co.uk.DataModels.Property_Info

    @foreach (var item in Model.RoomInfoes)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.RoomTypeID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.RoomDescription)
            </td>
        </tr>
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Gavin5511
  • 791
  • 5
  • 31
  • Look for some join examples for entity framework. Also, look at navigation properties... – Luke Dec 15 '15 at 11:00
  • 1
    Possible duplicate of [MVC 5 Multiple Models in a Single View](http://stackoverflow.com/questions/23536299/mvc-5-multiple-models-in-a-single-view) – Khalid Hussain Dec 15 '15 at 11:04

1 Answers1

2

Usually with Entity Framework, you get a Navigation Property on your entities if they have a foreign key relation.

This means you can access the property from the related type as well.

If your RoomInfos class has a property called RoomType of type RoomType (which is linked on the RoomTypeID) you can therefore access this in your model.

An example is shown below - the example is assuming you have a property on 'RoomType' called 'Name'.

@model manage.stayinflorida.co.uk.DataModels.Property_Info

@foreach (var item in Model.RoomInfoes)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.RoomType.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.RoomDescription)
        </td>
    </tr>
}

See this link for additional information about Navigation Properties.

Rob Aston
  • 816
  • 12
  • 19
  • This is exactly what i was after, thanks Rob. The link about Navigation Properties is also really useful. – Gavin5511 Dec 15 '15 at 11:12