默认情况下,渴望通过通用存储库中的实体框架加载所有内容

Heb*_*rda 5 c# linq asp.net-mvc entity-framework repository-pattern

我当前正在实现存储库模式,该模式允许我将类和上下文传递到常规存储库中。这很正常。我感兴趣的方法是Get and Find。该发现使我可以指定和“订购”一些“ where”语句和一些“ include”语句。这是理想的。

public class GeneralRepository<TEntity> : IGeneralRepository<TEntity> where TEntity : class
{

    readonly GamesContext context;
    readonly DbSet<TEntity> db;

    public GeneralRepository(GamesContext existingContext)
    {
        context = existingContext;
        db = context.Set<TEntity>();
    }

    public TEntity Get(object id)
    {
        return db.Find(id);
    }

    public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "")
    {
        IQueryable<TEntity> query = db;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
           (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
           return orderBy(query).ToList();
        }
        else
        {
           return query.ToList();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我的问题是,当我使用Get方法时,我宁愿它返回完整的对象图。暂时关闭了延迟加载,但是要加载,我需要添加相关的包含,只有这样才能击败执行通用存储库的对象。

我知道我可以只使用find方法,但是默认情况下使用get方法返回所有相关数据会更快。

有什么想法可以让我默认(全部加载)吗?

谢谢。

tra*_*max 6

这是一个坏主意。特别是如果您打算进一步构建应用程序。这是一条通往性能瓶颈和 OutOfMemory 异常的道路。

我发现通用存储库也是反模式的。随着时间的推移,你会意识到你需要在该Get方法中添加越来越多的函数,最终它只会复制DbContext.

事实上,您当前的实现并没有起到任何隔离的作用。为什么不直接使用 DbContext 呢?

我建议放弃通用内容的想法,并使用小的 Query 类以受控方式仅检索您需要的实体,而不是每个人的所有内容。看看这个

为了回答您的问题,实体框架没有提供IncludeAll. 您可以使用反射进行破解,但我不会在这里提供解决方案,因为这只是一种不好的做法。