Условное изменение запроса в LINQ
Мне надо взять ConfigurationService.ProductMaxLenght.Value продуктов, если ConfigurationService.ProductMaxLenght.Value == 0 надо брать все
var products = _dbProducts.GetAllDbSet()
.Take(ConfigurationService.ProductMaxLenght.Value)
.Include(p => p.Supplier)
.Include(p => p.Category)
.AsNoTracking();
Ответы (3 шт):
Автор решения: Alexander Petrov
→ Ссылка
Можно поступить просто:
int value = ConfigurationService.ProductMaxLenght.Value;
if (value == 0)
{
var products = _dbProducts.GetAllDbSet()
.Include(p => p.Supplier)
.Include(p => p.Category)
.AsNoTracking();
}
else
{
var products = _dbProducts.GetAllDbSet()
.Take(value)
.Include(p => p.Supplier)
.Include(p => p.Category)
.AsNoTracking();
}
Обратите внимание, что в запрос нельзя передавать выражение ConfigurationService.ProductMaxLenght.Value, а только простое значение (value).
Однако, linq-запросы бывают весьма длинными и такая запись будет слишком громоздкой. Поэтому составим запрос на лету:
IQueryable<T> products = _dbProducts.GetAllDbSet();
if (value != 0)
{
products = products.Take(value);
}
products = products
.Include(p => p.Supplier)
.Include(p => p.Category)
.AsNoTracking();
T - подставьте нужный тип сущности.
Автор решения: Chmelya
→ Ссылка
var products = _dbProducts.GetAllDbSet()
.Include(p => p.Supplier)
.Include(p => p.Category)
.AsNoTracking()
.AsEnumerable()
.TakeWhile((product, i) => i < ConfigurationService.ProductMaxLenght.Value
|| ConfigurationService.ProductMaxLenght.Value == 0);
Автор решения: Chmelya
→ Ссылка
Так как мы получаем IQueryable, можно составить следующий запрос, который выгрузит только необходимое количество:
var query = _dbProducts.GetAllAsQueryable();
query = _configuration.ProductMaxLenght.Value == 0 ?
query : query.Take(_configuration.ProductMaxLenght.Value);
var products = query
.Include(p => p.Supplier)
.Include(p => p.Category);