.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值