Entity Framework Core 未从参考表中加载相关数据

3
我的模型中有一个M:M关系,参考了https://www.entityframeworktutorial.net/efcore/configure-many-to-many-relationship-in-ef-core.aspx模型
public class Post
{
    [Key]
    public int Id { get; set; }
    [Display(Name = "Created By:")]
    public AppUser AuthorId { get; set; }
    [Required]
    public string Title { get; set; }
    public string metaTitle { get; set; }
    [Required]
    public string Body { get; set; }
    public bool Published { get; set; } 
    public bool ISFeatured { get; set; }
    public DateTime CretedDate { get; set; } = DateTime.Now;
    public DateTime ModifiyDate { get; set; } = DateTime.Now;
    public IList<Comment> Comments { get; set; }
    public IList<PostTag> PostTag { get; set; }
    public IList<PostCategory> PostCategory { get; set; }
    public IList<Images> Images { get; set; }

}

public class Tag
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public bool Published { get; set; } = true;
    public DateTime CretedDate { get; set; } = DateTime.Now;
    public DateTime ModifiyDate { get; set; } = DateTime.Now;
    public IList<PostTag> PostTag { get; set; }
    public IList<Images> Images { get; set; }


}

public class PostTag
{

    public int TagId { get; set; }
   
    public int PostId { get; set; }

    public Post Post { get; set; }

    public Tag Tag { get; set; }
    public AppUser AppUser { get; set; }

}

数据库上下文

modelBuilder.Entity<Post>()
        .HasMany(c => c.Comments)
        .WithOne(e => e.Post);

modelBuilder.Entity<PostCategory>().HasKey(p => new
{
    p.PostId,p.CategoryId
});

modelBuilder.Entity<PostCategory>()
    .HasOne(p => p.post).
    WithMany(p => p.PostCategory).
    HasForeignKey(p => p.PostId);

modelBuilder.Entity<PostCategory>().
    HasOne(p => p.Category).
    WithMany(p => p.PostCategory).
    HasForeignKey(p => p.CategoryId);

在控制器端获取所有帖子时,它能够获取所有帖子,但无法从相关的表中获取数据。例如标签、类别。
控制器:
public async Task<IActionResult> Index()
{
    return View(await _context.Post.ToListAsync());
}

enter image description here

更新操作

enter image description here

标签参考为空

enter image description here


尝试使用 _context.Post.Include(x => x.PostCategory) 等等。 - Vivek Nuna
EfCore默认使用急切加载,您需要使用.Include扩展来指定加载深度。https://dev59.com/qHA75IYBdhLWcg3wVXWv#29092178 - StuartLC
2个回答

2

我修改了但仍然没有显示数据,请检查图片2。 - ZCoder
它意味着 PostCategory 没有任何项目。 - Vivek Nuna
但是有一个快速的问题,你能检查一下下一个图片吗?它获取标签ID,但引用为空。 - ZCoder

2
使用ThenInclude来继续包含更深层次的相关数据。
 var posts = _context.Posts.Include(p => p.PostTag).ThenInclude(pt => pt.Tag).ToList();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接