Entity Framework Core не загружает связанные данные из справочной таблицы - PullRequest
3 голосов
/ 21 июня 2020

MY Model 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

Update Action

enter image description here

Tags reference is empty

введите описание изображения здесь

Ответы [ 2 ]

2 голосов
/ 22 июня 2020

Используйте ThenInclude, чтобы продолжить включение дополнительных уровней связанных данных.

 var posts = _context.Posts.Include(p => p.PostTag).ThenInclude(pt => pt.Tag).ToList();
2 голосов
/ 21 июня 2020

попробуйте _context.Post.Include(x => x.PostCategory) и т. Д.

Ссылка: https://docs.microsoft.com/en-us/ef/core/querying/related-data

...