ASP.NET Core EF 查询获取导航属性值,使用Include封装

时间:2023-03-08 17:52:25
     // 引用 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;
} }
}
public class FREEFUNC
{
[Key]
public long FFID { get; set; }
public Nullable<int> SCID { get; set; }
[ForeignKey("FUNCDEFINE")]
public int FID { get; set; }
public virtual FUNCDEFINE FUNCDEFINE { get; set; }
} public partial class FUNCDEFINE
{
[Key]
public int FID { get; set; }
public string FNAME { get; set; }
public int CANOPR { get; set; }
public int ISMENU { get; set; }
public int ISEDIT { get; set; }
public Nullable<int> FUNCTYPE { get; set; }
[ForeignKey("FUNCDEFINE")]
public Nullable<int> HIGHFID { get; set; }
public string ICON { get; set; }
public string CONTROLLER { get; set; }
public string ACTION { get; set; } public virtual FUNCDEFINE HIGHF { get; set; }
}

调用实例:

var list = FREEFUNCService.GetList().In("FUNCDEFINE", "FUNCDEFINE.HIGHF").ToList();

注:GetList()返回IQueryable<FREEFUNC>类型,IEnumerable<T>类型不支持Include方法,导航属性必须延迟查询时调用,最终生成连表查询sql语句。

另外不使用Include方法也可以获取导航属性,获得IQueryable对象延迟查询,再使用.Select查询时返回值中获取导航属性值,最终也会生成连表查询,foreach不支持。

.net core ef中 获取数据直接ToList() 导航属性为null。