C#C
C#4y ago
pyrodistic

MVC EF 5 - How to reference Model FK Properties?

Hello, I'm having some trouble figuring out the logic to reference FK table properties from a model.

I'm currently using the same model for index and details views for an entity. On the index I have:
@foreach (var item in Model) 
{
<tr>
  <td>@Html.DisplayFor(modelItem => item.Species.Name)</td>
...

This displays the Species.Name corretly in the column (Dog/Cat/...), where Species is a FK in the Pet class (public virtual Species Species { get; set; }).

On the details view I have:
<dt>@Html.DisplayNameFor(model => model.Species)</dt>
<dd>@Html.DisplayFor(model => model.Species)</dd>

For the index on the controller I do:
public async Task<IActionResult> Index(int id)
        {
            var dataContext = _petRepository.GetByOwner(id).Include("Species.Taxonomy");
            return View(await dataContext.ToListAsync());
        }

However on the details I'm unable to use Include:
public async Task<IActionResult> Details(int? id)
        {
            var pet = await _petRepository.GetByIdAsync(id.Value); // Cannot use .Include("Species.Taxonomy") here.

            return View(pet);
        }

The error I get is:
Error    CS1061    'Task<Pet>' does not contain a definition for 'Include' and no accessible extension method 'Include' accepting a first argument of type 'Task<Pet>' could be found (are you missing a using directive or an assembly reference?)

I'm using repository pattern and dependency injection. So the GetByIdAsync() is implemented on a general repository for all entities.
public async Task<T> GetByIdAsync(int id)
        {
            return await _context.Set<T>().AsNoTracking().FirstOrDefaultAsync(e => e.Id == id);
        }

While the GetByOwner() is specific to the Pets repository and returns a IQueryable<Pet>. Both repositories have the same references, tried to use .AsQueryable(), but have the same error. What am I doing wrong and how can I fix it?

Thanks in advance.
Was this page helpful?