简体   繁体   中英

ASP.NET Core relation is in database but is not retrieved

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);
    }
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM