ASP.NET Core EF Not Finding Navigation Property

asp.net-core entity-framework-core

Question

I'm making a survey app and have 3 domain models:

ActivityItem for each activity I want to ask about.

ItemResponse to tie together an ActivityItem and Checklist

Checklist to hold all the ItemResponses

I want to get the Checklist.ItemResponse.ActivityItem.Name in the view, but ActivityItem is always null despite the database having an ActivityItemId correctly filled. I just don't understand why the app can't Include() that table.

Here are snippets of my models:

ActivityItem

public class ActivityItem
{
        public int Id { get; set; }
        public string Name { get; set; }

ItemResponse

public class ItemResponse
{ 
    public int Id { get; set; }

    public int ChecklistId { get; set; }
    public virtual Checklist Checklist { get; set; }
    public int ActivityItemId { get; set; }
    public virtual ActivityItem ActivityItem { get; set; }

Checklist

public class Checklist
{
    public int Id { get; set; }
    public ICollection<ItemResponse> ItemResponses { get; set; }

I'm grateful for any help pointing me in the right direction about why this doesn't work. Thanks!

enter image description here

enter image description here

1
-2
1/25/2019 6:40:20 PM

Accepted Answer

This is because your navigation property name is ActivityItem but you are calling ActivityItems. So full query should be as follows:

var checkList = await _context.Checklist.Include(c => c.ItemResponses)
                     .ThenInclude(ir => ir.ActivityItem).ToListAsync();
1
1/25/2019 6:41:47 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow