Reputation: 4080
I have the following model :
public class Business
{
[Key]
public int BusinessId { get; set; }
public string Name {get;set;}
....
.....
....
[Display(Name = "Owner")]
public int OwnerId { get; set; }
[ForeignKey("OwnerId")]
public ApplicationUser Owner { get; set; }
}
In my controller I have the following function :
public async Task<IActionResult> Index()
{
return View(await _context.Business.ToListAsync());
}
and my view :
@model IEnumerable<ServiceProviderApp.Models.Business>
@{
ViewData["Title"] = "Business Engine";
}
.....
......
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
......
<td>
@Html.DisplayFor(modelItem => item.Owner.Name)
</td>
<td>
As you can understand, the Owner inside the Business is an Object. Therefore, when I try to access it in the view (item.Owner.Name) I don't get anything (null). I can change the query on the controller to return a record that is joined but then the model on the view won't be business any more.
I searched online but didn't find a good and clear explanation. Not sure why the EF doesn't bind the nested objects automatically.
One option that I saw on YouTube but I think that it sucks to do:
Link - https://www.youtube.com/watch?v=v1B3R-kb9CU
Upvotes: 0
Views: 418
Reputation: 4080
Solution : You need to use the include func in the controller :
public async Task<IActionResult> Index()
{
var business = _context.Business.Include("Owner");
return View(await business.ToListAsync());
}
Thanks to DanielShabi for the help.
Upvotes: 1