.ef core 多對對關係的關聯方法

最近在用.net core 重構博客,在使用ef core連表查詢時,遇到了一些問題。記錄一下。spa

關係:一個博客能夠有多個標籤,一個標籤能夠屬於多個博客,博客和標籤之間存在多對多的關係.net

下面是實體代碼(爲突出重點 省略部分屬性)code

BlogEntityblog

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>();
    }
}

LabelEntityget

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顯示加載 方法以下:string

以blog爲例it

blogService.GetAll().Include(u => u.BlogLabels).ThenInclude(bl=>bl.Label)

以上爲實體間多對多關聯時,連表查詢的方法。class

相關文章
相關標籤/搜索