.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)

以上为实体间多对多关联时,连表查询的方法。

原文地址:https://www.cnblogs.com/c-supreme/p/9955483.html