0

I am new to ASP.NET Core and I am trying to setup basic relationship with EntityFramework Core. I have a NavigationCategory class that has 1:M relationship with WebPage class. The relationship is understood by my DB (It has a foreign key) but when retrieving the WebPage from repository, it has no NavigationCategory, even though it has NavigationCategoryId set.

public class WebPage : BaseEntity
{
    private string _route;

    public string Title { get; set; }
    public string Body { get; set; }

    [ForeignKey("NavigationCategory")]
    public long NavigationCategoryId { get; set; }

    public NavigationCategory NavigationCategory { get; set; }

    public WebPage()
    {
    }
}

public class NavigationCategory : BaseEntity
{
    public string Title { get; set; }
    public IEnumerable<WebPage> WebPages { get; set; }

    public NavigationCategory()
    {
    }
}

This is simple BaseEntity:

public class BaseEntity
{
    public long Id { get; set; }
}

This is my DB context:

public class AppDataContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<KinderClass> KinderClasses { get; set; }
    public DbSet<Feed> Feeds { get; set; }
    public DbSet<NavigationCategory> NavigationCategories { get; set; }
    public DbSet<WebPage> WebPages { get; set; }

    public AppDataContext(DbContextOptions<AppDataContext> options) : base(options)
    {
        Database.EnsureCreated();
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<WebPage>()
            .HasOne(wp => wp.NavigationCategory)
                    .WithMany(c => c.WebPages)
                    .HasForeignKey(wp => wp.NavigationCategoryId);
    }
}
1
  • Read the documentation. Lazy loading is not supported yet, you have to explicitly or eager load (using Include / ThenInclude) the related data. Commented Apr 21, 2017 at 18:57

1 Answer 1

1

You need to explicitly include any navigation property you want included when you fetch entities using EF Core. For example, update your query as follows:

var webpage = dbContext.WebPages
  .Include(w => w.NavigationCategory)
  .FirstOrDefault();

Note, you need these two namespaces, at minimum:

using Microsoft.EntityFrameworkCore;
using System.Linq;

Learn more about loading related data and why lazy loading shouldn't be used in web apps.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.