我是ASP.NET Core的新手,我正在尝试与EntityFramework Core建立基本关系。我有一个NavigationCategory类与WebPage类有1:M的关系。我的DB(它有一个外键)可以理解这种关系,但是当从存储库中检索WebPage时,它没有NavigationCategory,即使它已经设置了NavigationCategoryId。
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; }
}
这是我的数据库上下文:
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 :(得分:0)
使用EF Core获取实体时,需要显式包含要包含的任何导航属性。例如,更新您的查询,如下所示:
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。