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)

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

  • 相关阅读:
    JavaScript 操作CSS
    源码搭建LAMP服务器
    Modified 2 color sort
    python的网络库
    找出有序整数数组中下标与值相同的所有元素
    sql 查看Oralce 数据库连接状态
    oracle 快闪 sql
    Sql server dblink
    昆山桶装水/免费送货上门/
    C# Tostring() 格式大全 [转]
  • 原文地址:https://www.cnblogs.com/c-supreme/p/9955483.html
Copyright © 2011-2022 走看看