Entity Framework 包括不包括相关实体

Entity Framework Include aren't including related entities

我的存储库中有以下代码。由于某种原因,query.Include() 方法不起作用,结果中不包含相关实体。仔细检查 属性 名称是否正确传递。也许我以错误的方式使用它?有什么想法吗?

public IEnumerable<TEntity> Get(
        Func<TEntity, bool> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> order = null,
        string includedProperties = null)
    {
        IQueryable<TEntity> query = _context.Set<TEntity>();

        if (filter is not null)
        {
            query = query.Where(filter).AsQueryable();
        }

        if (order is not null)
        {
            query = order(query);
        }

        if (includedProperties is not null)
        {
            var properties = includedProperties.Split(',', StringSplitOptions.RemoveEmptyEntries);

            foreach (var property in properties)
            {
                query.Include(property);
            }
        }

        return query;
    }

我认为您需要更改为以下内容

query =query.Include(property);

感谢@Alen.Toma 发现原始代码中缺失的分配。

在原来的代码中,一旦我们使用Enumerable.Where(...),原来对数据库的查询就不能再修改了,因为我们已经在C#中过滤了对象。这意味着 query.Include 作用于 Enumerable.Where 的结果, 而不是 作用于原始数据库查询,因此没有预期的效果。

完整修改代码:

public IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> order = null,
        string includedProperties = null)
    {
        IQueryable<TEntity> query = _context.Set<TEntity>();

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

        if (order is not null)
        {
            query = order(query);
        }

        if (includedProperties is not null)
        {
            var properties = includedProperties.Split(',', StringSplitOptions.RemoveEmptyEntries);

            foreach (var property in properties)
            {
                query = query.Include(property);
            }
        }

        return query;
    }