联接或可变DBContext存储库通用c# [英] Join or Mutible DBContext Repository Generic c#
问题描述
我有通用的存储库,可以在其中执行Get,Update,Insert的方法.
I have repository generic where I do method as Get,Update,Insert.
我使用这种方法从数据库中的表中获取数据.
I get a data from table in data base I use this method.
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;
}
我仅在一张表中获取数据时,这是我的代码:
I when get data only a one table this is my code:
var collecProducts = repository.Get<Products>(c => true);
我的问题是什么时候我想买两台平板电脑,我该怎么办?我找到了这段代码,但是非常慢.
My problem is when I want get two tablet How I do this?. I find this code but is very slow.
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所需的数据.
The problem this code is that get all data de products and category and I want from SQL Server only data necessary for example as join TSQL.
select p.idProducts from products p join category c on p.idCategory = c.idCategory
总而言之,自存储库泛型以来,如何使用联接获取数据.
In conclusion How I could get data use join since repository generyc.
推荐答案
您找到的解决方案很慢,因为存储库方法正在立即实现/执行查询,而不是允许延迟执行.尝试从存储库方法中的查询中删除".ToList()":
The solution you found is slow because the repository method is materializing/executing the query immediately instead of allowing deferred execution to occur. Try removing the ".ToList()" from the query within the repository method:
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;
}
这将使您能够构成和构造更高阶的查询,而无需立即将整个表拉入内存.
This will allow you to compose and construct higher order queries without pulling the whole table into memory immediately.
这篇关于联接或可变DBContext存储库通用c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!