How can I dynamically add Include to an ObjectSet <Entity> using C #?
I want to add Include dynamically from params[] input. How can i do this?
This is my code.
IQueryable<Work> query = this.ObjectContext.Works .Include("EmployeeSender.Person") .Include("EmployeeReceiver.Person") .Include("WorkCode") .Include("WorkFlowStep.WorkFlowFormState") .Include("WorkFlow") .Include("WorkRoot.EmployeeSender.Person") .Include("WorkParent"); +4
3 answers
You can combine the L-Three answer with the extension method in the next question.
Using .Include () when attaching to a view using Entity Framework
public static IQueryable<T> Include<T>(this IQueryable<T> sequence, params string[] includes) { var objectQuery = sequence as ObjectQuery<T>; if (objectQuery != null){ foreach(item in includes){ objectQuery.Include(item); } return objectQuery; } return sequence; } Then you can use include, for example:
IQueryable<Work> query = null; query = this.ObjectContext.Works.Include("Something", "Whatever"); +3
Lazy loading still doesn't work in EF Core. See here .
Alternatively, you can use active download.
Read this article
Below is the extension method that I created to achieve the desired download.
Extension Method:
public static IQueryable<TEntity> IncludeMultiple<TEntity, TProperty>( this IQueryable<TEntity> source, List<Expression<Func<TEntity, TProperty>>> navigationPropertyPath) where TEntity : class { foreach (var navExpression in navigationPropertyPath) { source= source.Include(navExpression); } return source.AsQueryable(); } Repository call:
public async Task<TEntity> FindOne(ISpecification<TEntity> spec) { return await Task.Run(() => Context.Set<TEntity>().AsQueryable().IncludeMultiple(spec.IncludeExpression()).Where(spec.IsSatisfiedBy).FirstOrDefault()); } Using:
List<object> nestedObjects = new List<object> {new Rules()}; ISpecification<Blog> blogSpec = new BlogSpec(blogId, nestedObjects); var challenge = await this._blogRepository.FindOne(blogSpec); Dependencies:
public class BlogSpec : SpecificationBase<Blog> { readonly int _blogId; private readonly List<object> _nestedObjects; public ChallengeSpec(int blogid, List<object> nestedObjects) { this._blogId = blogid; _nestedObjects = nestedObjects; } public override Expression<Func<Challenge, bool>> SpecExpression { get { return blogSpec => blogSpec.Id == this._blogId; } } public override List<Expression<Func<Blog, object>>> IncludeExpression() { List<Expression<Func<Blog, object>>> tobeIncluded = new List<Expression<Func<Blog, object>>>(); if (_nestedObjects != null) foreach (var nestedObject in _nestedObjects) { if (nestedObject is Rules) { Expression<Func<Blog, object>> expr = blog => blog.Rules; tobeIncluded.Add(expr); } } return tobeIncluded; } Would be happy if that helps. Please note that this is not a production code.
+1