EF LINQ include multiple and nested entities

后端 未结 6 1158
猫巷女王i
猫巷女王i 2020-11-28 03:25

Ok, I have tri-leveled entities with the following hierarchy: Course -> Module -> Chapter

Here was the original EF LINQ statement:

Course course = db         


        
6条回答
  •  爱一瞬间的悲伤
    2020-11-28 03:44

    One may write an extension method like this:

        /// 
        /// Includes an array of navigation properties for the specified query 
        /// 
        /// The type of the entity
        /// The query to include navigation properties for that
        /// The array of navigation properties to include
        /// 
        public static IQueryable Include(this IQueryable query, params string[] navProperties)
            where T : class
        {
            foreach (var navProperty in navProperties)
                query = query.Include(navProperty);
    
            return query;
        }
    

    And use it like this even in a generic implementation:

    string[] includedNavigationProperties = new string[] { "NavProp1.SubNavProp", "NavProp2" };
    
    var query = context.Set()
    .Include(includedNavigationProperties);
    

提交回复
热议问题