// 引用 using Microsoft.EntityFrameworkCore;
        // 摘要:
        //     Specifies related entities to include in the query results. The navigation property
        //     to be included is specified starting with the type of entity being queried (TEntity).
        //     Further navigation properties to be included can be appended, separated by the
        //     '.' character.
        //
        // 参数:
        //   source:
        //     The source query.
        //
        //   navigationPropertyPath:
        //     A string of '.' separated navigation property names to be included.
        //
        // 类型参数:
        //   TEntity:
        //     The type of entity being queried.
        //
        // 返回结果:
        //     A new query with the related data included.
        public static IQueryable<TEntity> Include<TEntity>([NotNullAttribute] this IQueryable<TEntity> source, [NotNullAttribute][NotParameterized] string navigationPropertyPath) where TEntity : class;

core中提供的扩展方法Include有两个重载方法,我们这里使用第一个重载方法,传参数导航属性名字,返回IQueryable<TEntity>,多对多导航属性,二级导航属性需要用‘.’点分隔符连接,提供完整导航属性名称。

下面是我封装的扩展方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace System
{
    public static class IQueryableExtensions
    {
        /// <summary>
        /// 导航属性,参数:导航属性名称字符串,支持多表查询
        /// 多级导航属性:“属性名.属性名”  用‘.’连接
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="Properts"></param>
        /// <returns></returns>
        public static IQueryable<T> In<T>(this IQueryable<T> obj, params string[] Properts) where T : class
        {
            IQueryable<T> data = obj;
            foreach (var prop in Properts)
            {
                data = data.Include(prop);
            }
            return data;
        }

    }
}
View Code

相关文章: