Entity Framework core .Include() issue

后端 未结 4 1077
长发绾君心
长发绾君心 2021-02-18 22:05

Been having a play about with ef core and been having an issue with the include statement. For this code I get 2 companies which is what i expected.



        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-18 22:52

    Lazy loading is not yet possible with EF Core. Refer here.

    Alternatively you can use eager loading.

    Read this article

    Below is the extension method i have created to achieve the eager loading.

    Extension Method:

    public static IQueryable IncludeMultiple(
        this IQueryable source,
        List>> navigationPropertyPath) where TEntity : class
    {
        foreach (var navExpression in navigationPropertyPath)
        {
            source= source.Include(navExpression);
        }
        return source.AsQueryable();
    }
    

    Repository Call:

    public async Task FindOne(ISpecification spec)
    {
        return await Task.Run(() => Context.Set().AsQueryable().IncludeMultiple(spec.IncludeExpression()).Where(spec.IsSatisfiedBy).FirstOrDefault());
    }
    

    Usage:

    List nestedObjects = new List {new Rules()};
    
    ISpecification blogSpec = new BlogSpec(blogId, nestedObjects); 
    
    var challenge = await this._blogRepository.FindOne(blogSpec);
    
    

    Dependencies:

    public class BlogSpec : SpecificationBase
    {
        readonly int _blogId;
        private readonly List _nestedObjects;
    
        public ChallengeSpec(int blogid, List nestedObjects)
        {
            this._blogId = blogid;
            _nestedObjects = nestedObjects;
        }
    
        public override Expression> SpecExpression
        {
            get { return blogSpec => blogSpec.Id == this._blogId; }
        }
    
        public override List>> IncludeExpression()
        {
            List>> tobeIncluded = new List>>();
            if (_nestedObjects != null)
                foreach (var nestedObject in _nestedObjects)
                {
                    if (nestedObject is Rules)
                    {
                        Expression> expr = blog => blog.Rules;
                        tobeIncluded.Add(expr);
                    }
                    
                }
    
            return tobeIncluded;
        }
    }
    
    

    Will be glad if it helps. Please note this is not a production ready code.

    提交回复
    热议问题