// 引用 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>,多對多導航屬性,二級導航屬性須要用‘.’點分隔符鏈接,提供完整導航屬性名稱。sql
下面是我封裝的擴展方法:app
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; } }
調用實例:ide
var list = FREEFUNCService.GetList().In("FUNCDEFINE", "FUNCDEFINE.HIGHF").ToList();
注:GetList()返回IQueryable<FREEFUNC>類型,IEnumerable<T>類型不支持Include方法,導航屬性必須延遲查詢時調用,最終生成連表查詢sql語句。this
另外不使用Include方法也能夠獲取導航屬性,得到IQueryable對象延遲查詢,再使用.Select查詢時返回值中獲取導航屬性值,最終也會生成連表查詢,foreach不支持。spa
.net core ef中 獲取數據直接ToList() 導航屬性爲null。.net