实体框架核心未从参考表加载相关数据

时间:2020-06-21 07:25:35

标签: c# asp.net-mvc asp.net-core

MY模型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

2 个答案:

答案 0 :(得分:2)

尝试\(\([A-Z]\{2}-\)\@<=\d\d\d\)\|\([A-Z]\{2}\(-\d\d\d\)\@=\) ,依此类推。

参考: https://docs.microsoft.com/en-us/ef/core/querying/related-data

答案 1 :(得分:2)

使用ThenInclude继续包含更多级别的相关数据。

 var posts = _context.Posts.Include(p => p.PostTag).ThenInclude(pt => pt.Tag).ToList();