zoukankan      html  css  js  c++  java
  • .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)

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

  • 相关阅读:
    Collection与Collections的区别
    Java容器基础概况
    IO与NIO的区别
    BIO、NIO、AIO的区别
    Java中的IO流
    Java中的抽象类
    String常用方法解析
    字符串反转
    vue路由传参
    flask框架(八)—自定义命令flask-script、多app应用、wtforms表单验证、SQLAIchemy
  • 原文地址:https://www.cnblogs.com/c-supreme/p/9955483.html
Copyright © 2011-2022 走看看