最近在用.net core 重構博客,在使用ef core連表查詢時,遇到了一些問題。記錄一下。
關系:一個博客可以有多個標簽,一個標簽可以屬於多個博客,博客和標簽之間存在多對多的關系
下面是實體代碼(為突出重點 省略部分屬性)
BlogEntity
namespace Blog.Service.Entities { public class BlogEntity:BaseEntity { public string Title { get; set; } public string Content { get; set; } public virtual List<BlogLabelEntity> BlogLabels { get; set; } = new List<BlogLabelEntity>(); } }
LabelEntity
namespace Blog.Service.Entities { public class LabelEntity:BaseEntity { public string Title { get; set; } public string IconUrl { get; set; } public virtual List<BlogLabelEntity> BlogLabels { get; set; } = new List<BlogLabelEntity>(); } }
BlogLabelEntity
namespace Blog.Service.Entities { public class BlogLabelEntity:BaseEntity { public long BlogId { get; set; } public virtual BlogEntity Blog { get; set; } public long LabelId { get; set; } public virtual LabelEntity Label { get; set; } } }
在查詢博客時同時將標簽也查詢出來,使用Include顯示加載 方法如下:
以blog為例
blogService.GetAll().Include(u => u.BlogLabels).ThenInclude(bl=>bl.Label)
以上為實體間多對多關聯時,連表查詢的方法。