.net core ef 连表查询

Information和TypeInfo连表查询

类似:

select st.Title1,si.* from [Star_Information] si left join Star_TypeInfo st on si.typeId2=st.id

先在EfCoreDbContext.cs配置

  protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            //TypeInfo 连表查询配置
            builder.Entity<Information>()
            .HasOne(si => si.TypeInfo)
            .WithMany()
            .HasForeignKey(si => si.TypeId2);// 跟TypeInfo表相关联的TypeId2
        }

在Information.cs实体类新增 public TypeInfo TypeInfo { get; set; } // 导航属性 

 

接口实现

  /// <summary>
        /// 获取信息列表
        /// </summary>
        /// <param name="channel">调用参数</param>
        /// <param name="pageSize">每页记录数。必须大于等于1</param>
        /// <param name="pageIndex">页码。首页从1开始,页码必须大于等于1</param>
        /// <param name="typeIds">分类Id集</param>
        /// <param name="typeInfoIds">多选分类Id集</param>
        /// <param name="auditIds">审核Id集</param>
        /// <param name="keywords">搜索关键词</param>
        /// <returns></returns>
        [HttpGet]
        [Authorize("Manage_View")]
        public async Task<MessageDto> List(string channel, int pageSize, int pageIndex, string typeIds = "", string typeInfoIds = "", string auditIds = "", string keywords = "")
        {
            var parameter = (InformationParameter)await _adminMenuService.GetParameter(channel, new InformationParameter());
            if (parameter.Channel == "")
            {
                return new MessageDto { Message = "信息不存在" };
            }
            var where = PredicateBuilder.True<Information>();
            where = where.And(w => w.Channel == parameter.Channel && w.WebSiteId == _authorityModel.WebSite.Id);
            if (!string.IsNullOrEmpty(typeIds))
            {
                var lastPathId = typeIds.Split(',').LastOrDefault();
                where = where.And(w => w.TypeIdPath.Contains(lastPathId));
            }
            if (!string.IsNullOrEmpty(typeInfoIds))
            {
                var lastPathId = typeInfoIds.Split(',').LastOrDefault();
                where = where.And(w => w.TypeIdStrPath.Contains(lastPathId));
            }
            if (!string.IsNullOrEmpty(auditIds) && StringHelper.IsNumber(auditIds.Split(',').LastOrDefault()))
            {
                var lastPathId = long.Parse(auditIds.Split(',').LastOrDefault());
                where = where.And(w => w.AuditStatus == lastPathId);
            }
            if (!string.IsNullOrEmpty(keywords))
            {
                //连表查询TypeInfo的标题
                where = where.And(w => w.TypeInfo.Title1.Contains(keywords));
            }

            //联表查询
            var infoList = await _informationService.GetListAsync(pageSize, pageIndex, where
                , order => order.OrderByDescending(o => o.IsTop).ThenBy(o => o.Sort.Length).ThenBy(o => o.Sort).ThenByDescending(o => o.ReleaseDate)
                 );


            //联表查询 这个可以直接查出已经关联的人才表
            //var infoList = await _informationService.GetListAsync(pageSize, pageIndex, where,
            //    order => order.OrderByDescending(o => o.IsTop).ThenBy(o => o.Sort.Length).ThenBy(o => o.Sort).ThenByDescending(o => o.ReleaseDate)
            //    , info => info.Include(i => i.TypeInfo));

            var totleCount = await _informationService.CountAsync(where);
            var listData = _mapper.Map<List<Information>, List<InformationDto>>(infoList);
            var typeInfoList = await _typeInfoService.GetListAsync(0, w => w.Channel == parameter.TypeChannel && w.WebSiteId == _authorityModel.WebSite.Id, order => order.OrderBy(o => o.Sort));
            foreach (var item in listData)
            {
                //如果有关联简介的id
                if (item.TypeId2!=0)
                {
                    var typeInfo = await _typeInfoService.GetAsync(item.TypeId2);

                    if (typeInfo!=null)
                    {                     
                        item.Type2Name= typeInfo.Title1;
                        item.Type2Img = typeInfo.PicURL1;
                    }

                }

                if (!string.IsNullOrEmpty(item.TypeIdPath))
                {
                    item.TypeIdPathName = new List<string>();
                    var itemTypeList = typeInfoList.Where(w => item.TypeIdPath.Contains(w.Id.ToString()));
                    foreach (var type in itemTypeList)
                    {
                        item.TypeIdPathName.Add(type.Title1);

                        if (item.Channel == "ScientificResearchPlatform")
                        {
                            string[] attrid = item.TypeIdPath.Split(',');

                            if (type.DisplayMode == 0)
                            {
                                if (item.TypeIdPath != "")
                                {
                                    if (attrid.Length > 1)
                                    { 
                                    item.Url = "http://103.236.254.221:20002/#/Platform/" + attrid[0] + "/" + attrid[1] + "/0/1";
                                    }
                                }
                            }
                            else if (type.DisplayMode == 1)
                            {
                                item.Url = "http://103.236.254.221:20002/#/NewsInfo/ScientificResearchPlatform/" + item.Id + "/" + attrid[0] + "";
                            }
                            else if (type.DisplayMode == 2)
                            {
                                item.Url = "";
                            }
                        }
                    }
                }


            }



            return new MessageDto { Success = true, Data = new { listData, totleCount } };

        }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
.NET Core中,Entity Framework CoreEF Core)是一种广泛使用的对象关系映射(ORM)框架,用于与数据库进行交互。它提供了一组语法和API,用于操作数据库、定义实体模型和执行查询等操作。 下面是一些常见的EF Core语法: 1. 数据库上下文(DbContext):数据库上下文是与数据库交互的主要入口点。通过继承`DbContext`类并指定实体模型,可以创建自定义的数据库上下文类。 2. 实体(Entity):实体是映射到数据库表的对象模型。在EF Core中,可以使用POCO(Plain Old CLR Object)类作为实体。 3. 数据迁移(Data Migration):EF Core提供了数据迁移工具,用于管理数据库模式和结构的变化。通过命令行工具或API,可以创建、应用和回滚数据库迁移。 4. LINQ查询:通过使用LINQ(Language-Integrated Query)语法,可以在EF Core中执行强类型的查询操作。LINQ提供了一组丰富的操作符和方法,用于筛选、排序和投影数据。 5. 关系映射:EF Core支持多种关系映射类型,如一对一、一对多和多对多等。可以使用数据注解或Fluent API来配置实体之间的关系。 6. 查询跟踪(Query Tracking):默认情况下,EF Core会跟踪查询结果并自动更新上下文中的实体。可以使用`.AsNoTracking()`方法来禁用查询跟踪。 7. 异步操作:EF Core提供了异步的API,用于执行数据库操作。通过使用`async`和`await`关键字,可以在异步环境中执行数据库查询和保存操作。 这只是EF Core语法的一小部分。如果您有具体的EF Core问题或需要更详细的信息,请告诉我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值