[英]Entity Framework Core not loading related data from reference table
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);
在 controller 上,側取所有帖子,它帶來了所有帖子,但沒有從相關表中獲取任何數據。 示例標簽、類別
Controller
public async Task<IActionResult> Index()
{
return View(await _context.Post.ToListAsync());
}
更新操作
標簽引用為空
嘗試_context.Post.Include(x => x.PostCategory)
等等。
參考: https://docs.microsoft.com/en-us/ef/core/querying/related-data
使用 ThenInclude 繼續包括更多級別的相關數據。
var posts = _context.Posts.Include(p => p.PostTag).ThenInclude(pt => pt.Tag).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.