问题
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();
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.
回答1:
Thank,
I find a form get this result for examenple Product and Category in repository Generic through include.
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;
}
With include you can string for example Product->Category and get this object.
Thanks
回答2:
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.
来源:https://stackoverflow.com/questions/49832598/join-or-mutible-dbcontext-repository-generic-c-sharp