我的模型中有一个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());
}
更新操作
标签参考为空
_context.Post.Include(x => x.PostCategory)
等等。 - Vivek Nuna