加入或Mutible DBContext存储库通用c#

时间:2018-04-14 14:38:35

标签: c# entity-framework linq join repository-pattern

我有存储库通用,我在其中执行Get,Update,Insert等方法。

我从数据库中的表中获取数据我使用此方法。

 public IEnumerable<typeEntity> Get<typeEntity>(Expression<Func<typeEntity, bool>> newObjectEntity,int page, int rowsByPage) where typeEntity : class
    {
       List<typeEntity> Result = null;
            Result = Context.Set<typeEntity>().Where(newObjectEntity).OrderBy(m => true).Skip<typeEntity>(5 * (page - 1)).Take<typeEntity>(rowsByPage).ToList<typeEntity>();
        return Result;
    }

我在获取数据时只有一个表,这是我的代码:

var collecProducts = repository.Get<Products>(c => true);

我的问题是什么时候我想要两片我怎么做?我发现这段代码但速度很慢。

var collecProducts = repository.Get<Products>(c => true);
var collecCategory = repository.Get<Category>(c => true);

var collectProductToCategory = (from p in collecProducts
                                           join c in collecCategory on p.idCategory equals c.idCategory).ToList();

此代码的问题在于获取所有数据产品和类别,并且我只想从SQL Server获取必要的数据,例如作为连接TSQL。

select p.idProducts from products p join category c on p.idCategory = c.idCategory

总结我如何从存储库generyc获取数据使用加入。

2 个答案:

答案 0 :(得分:0)

感谢,

我找到一个表单,通过include。

获取存储库Generic中的examenple产品和类别的结果
 public IEnumerable<typeEntity> Get<typeEntity>(Expression<Func<typeEntity, bool>> newObjectEntity,int page, int rowsByPage, string include) where typeEntity : class
    {
       List<typeEntity> Result = null;
            Result = Context.Set<typeEntity>().Where(newObjectEntity).include(include).OrderBy(m => true).Skip<typeEntity>(5 * (page - 1)).Take<typeEntity>(rowsByPage).ToList<typeEntity>();
        return Result;
    }

使用include,您可以将字符串作为示例Product-&gt; Category并获取此对象。

由于

答案 1 :(得分:0)

您找到的解决方案很慢,因为存储库方法立即实现/执行查询,而不是允许延迟执行。尝试删除&#34; .ToList()&#34;来自存储库方法中的查询:

public IEnumerable<typeEntity> Get<typeEntity>(Expression<Func<typeEntity, bool>> newObjectEntity,int page, int rowsByPage) where typeEntity : class
{
   IEnumerable<typeEntity> Result = null;
        Result = Context.Set<typeEntity>().Where(newObjectEntity).OrderBy(m => true).Skip<typeEntity>(5 * (page - 1)).Take<typeEntity>(rowsByPage);
    return Result;
}

这将允许您编写和构造更高阶的查询,而无需立即将整个表拉入内存。

相关问题