简体   繁体   English

在 foreach 中使用 EF Core 包含方法可能是一个性能问题

[英]Is using EF Core include method inside a foreach can be a performance issue

These days I am working on a project, and this project depends on another project that will play the repository, my repository project based on Generic Repository pattern .这些天我在做一个项目,这个项目依赖于另一个将播放存储库的项目,我的存储库项目基于Generic Repository pattern In my repository project I created a method that will get all data from a received entity and load data from selected entities in a received expression.在我的存储库项目中,我创建了一个方法,该方法将从接收的实体中获取所有数据,并从接收的表达式中的选定实体加载数据。

My method:我的方法:

public List<TEntity> GetAll<TEntity>(params Expression<Func<TEntity, object>>[] expressions) where TEntity : class
{
    var result = new List<TEntity>();

    foreach (var expression in expressions)
    {
        result = Context.Set<TEntity>().Include(expression).ToList();
    }

    return result;
}

The question:问题:

As you will notice in the above method I used Include method inside an iteration ( Foreach ), so my question is: is that using of Include inside foreach have a performance issue or any other problem?正如您将在上述方法中注意到的那样,我在迭代( Foreach )中使用了Include方法,所以我的问题是:在foreach中使用Include是否存在性能问题或任何其他问题?

Probably you need this:可能你需要这个:

public List<TEntity> GetAll<TEntity>(params Expression<Func<TEntity, object>>[] expressions) where TEntity : class
{
    var query = Context.Set<TEntity>().AsQueryable();

    foreach (var expression in expressions)
    {
        query = query.Include(expression);
    }

    return query.ToList();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM