0

我是新来的ASP.NET核心,我试图建立与EntityFramework核心的基本关系。我有一个与WebPage类具有1:M关系的NavigationCategory类。我的数据库(它有一个外键)可以理解这种关系,但是当从存储库中检索WebPage时,它没有NavigationCategory,即使它已经设置了NavigationCategoryId。ASP.NET核心关系在数据库中,但没有检索

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() 
    { 
    } 
} 

这是简单的BaseEntity:

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

这是我的DB背景:

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

阅读[文档](https://docs.microsoft.com/en-us/ef/core/querying/related-data)。目前还不支持延迟加载,您必须明确或急切地加载(使用'Include' /'ThenInclude')相关数据。 –

+0

哦,非常感谢:) –

回答

0

你需要明确包括要包括任何导航属性,当你使用EF核心获取实体。例如,如下更新查询:

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

注意,你需要这两个命名空间,最低:

using Microsoft.EntityFrameworkCore; 
using System.Linq; 

详细了解loading related data,为什么lazy loading shouldn't be used in web apps