然后包含在EF Core查询中无法识别

时间:2017-09-01 12:47:58

标签: c# entity-framework linq entity-framework-core

我的IQueryable看起来像这样:

 IQueryable<TEntity> query = context.Set<TEntity>();
query = query.Include("Car").ThenInclude("Model");
  

'IQueryable'不包含'ThenInclude'的定义   没有扩展方法'ThenInclude'接受第一个参数   类型'IQueryable'可以找到(你错过了使用   指令或程序集引用?)

我需要所有参考资料:

using Content.Data.Models;    
using Microsoft.EntityFrameworkCore;    
using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Linq.Expressions;    
using System.Threading.Tasks;   

为什么它不能识别ThenInclude?

查询:

[Content.Data.Models.Article]).Where(x => (((x.BaseContentItem.SiteId == value(Content.Business.Managers.ArticleManager+<>c__DisplayClass8_0).id) AndAlso x.BaseContentItem.IsActive) AndAlso x.BaseContentItem.IsLive)).Include("BaseContentItem").Include("BaseContentItem.TopicTag").Include("MainImage")}

在我加入.Include("BaseContentItem.TopicTag")部分后失败。

所以我只是读到了通用存储库,你就失去了ThenInclude。我正在使用这个通用代表:

public class ReadOnlyRepository<TContext> : IReadOnlyRepository
            where TContext : DbContext
    {
        protected readonly TContext context;

        public ReadOnlyRepository(TContext context)
        {
            this.context = context;
        }

        private IQueryable<TEntity> GetQueryable<TEntity>(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = null,
            int? skip = null,
            int? take = null)
            where TEntity : class, IEntity
        {
            includeProperties = includeProperties ?? string.Empty;
            IQueryable<TEntity> query = context.Set<TEntity>();

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                query = orderBy(query);
            }

            if (skip.HasValue)
            {
                query = query.Skip(skip.Value);
            }

            if (take.HasValue)
            {
                query = query.Take(take.Value);
            }

            return query;
        }

2 个答案:

答案 0 :(得分:12)

仅当您对lambda表达式参数使用ThenInclude重载时,

Include才可用:

query = query.Include(e => e.Car).ThenInclude(e => e.Model);

当您使用字符串参数的Include重载时,不需要ThenInclude,因为您可以在传递的字符串中指定整个属性路径:

query = query.Include("Car.Model");

答案 1 :(得分:4)

您的问题可能是缺少对Microsoft.EntityFrameworkCore.Relational的引用?

这可以通过程序包管理器添加。

还请确保您使用的是Microsoft.EntityFrameworkCore命名空间中的.include,而不是其他.include(没有.ThenInclude)。