Reputation: 975
I'm in ASP.NET using MVC scaffolding. I have a table that has a foreign key in which it has a foreign key I wish to display too. It gets a little confusing.
I have a device table that is linked to a ManufacturerModel table by a foreign key of ManufacturerModelID. The ManufacturerModel table is comprised of the primary key of ManufacurerModelID, a foreign key of ManufacturerID (from a Manufacturer table) and just a Model field. In my device Index screen I would like to display the Device's Manufacturer (from the Manufacturer table) and Model. Currently it will display the model correctly however when I try to add the manufacturer I received the entire ManufacturerModel record including column headers.
In the Device Controller ActionResult for Index() I have the following:
var devices = db.Devices.Include(d => d.DeviceType).Include(d => d.ManufacturerModel);
return View(devices.ToList());
In my Device Index I have the following for Manufacturer and Model
<th>
@Html.DisplayNameFor(model => model.ManufacturerModel.ManufacturerID)
</th>
<th>
@Html.DisplayNameFor(model => model.ManufacturerModel.Model)
</th>
Upvotes: 0
Views: 2535
Reputation: 4030
So, If I understood correctly, you have
Device -[ManufacturerModel]-> ManufacturerModel -[ManufacturerID]-> Manufacturer
If this is the case, and the foreign keys are correctly defined, you have a class in your model called Device
which has a property called ManufacturerModel
which has a property called Manufacturer
which contains properties related to the columns of the Manufacturer table. I will asume that you have a Name
property and column respectively and you want to display something like
<tr>
<th>
@Html.DisplayNameFor(model => model.ManufacturerModel.Manufacturer.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.ManufacturerModel.Model)
</th>
</tr>
<tr>
<td>@model.ManufacturerModel.Manufacturer.Name</td>
<td>@model.ManufacturerModel.Model</td>
<tr>
then, when creating the query, you will have to also include (join) the Manufacturer
table like
var devices = db.Devices
.Include(d => d.DeviceType)
.Include(d => d.ManufacturerModel)
.Include(d => d.ManufacturerModel.Manufacturer)
Upvotes: 1
Reputation: 1402
It is because of you tables relations. your Device doesn't have direct relation to ManufacturerModel. Your relation is based on: devices > DeviceType > ManufacturerModel. Try
var devices = db.Devices.Include(d => d.DeviceType).Include(d => d.DeviceType.ManufacturerModel);
Upvotes: 0