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


最近在用.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)

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM