C# 基于LINQ的产品表过滤
我在一个MVC应用程序中使用EF代码优先后端。我有一个产品表,我想分页和过滤的类别或品牌 我不确定做这件事的最佳方法是什么,请随意指出我的愚蠢之处,但现在我有了上面页面的以下ViewModel:C# 基于LINQ的产品表过滤,c#,entity-framework,linq,C#,Entity Framework,Linq,我在一个MVC应用程序中使用EF代码优先后端。我有一个产品表,我想分页和过滤的类别或品牌 我不确定做这件事的最佳方法是什么,请随意指出我的愚蠢之处,但现在我有了上面页面的以下ViewModel: public class InventoryReportViewModel { public SearchViewModel Search { get; set; } // 2 string props [Type and Term] public IEnumerable<Product
public class InventoryReportViewModel
{
public SearchViewModel Search { get; set; } // 2 string props [Type and Term]
public IEnumerable<ProductViewModel> Products { get; set; }
public PaginationViewModel Pagination { get; set; } // 3 int props [currentPage, recordsPerPage, totalRecords]
}
但是上面这些似乎不起作用!我在ViewModel中返回了200个产品,而我应该只得到10个,因为这是我的记录页面
我哪里出错了?LINQ方法不会修改应用它们的序列,它们会生成新序列作为返回值。您需要使用LINQ操作的返回值
activeProducts
将不受方法调用的影响
例如:
var activeProducts = _context.Products.Where(p => !p.IsDeleted);
if (!string.IsNullOrEmpty(searchTerm))
{
if (searchType == "category")
{
// See the change here?
activeProducts = activeProducts
.Where(p => string.Equals(
p.Category.Name,
searchTerm.Trim(),
StringComparison.CurrentCultureIgnoreCase))
.OrderBy(p => p.Category.Name)
.Skip(_recordsPerPage * (page - 1))
.Take(_recordsPerPage);
}
else
{
// Here.
activeProducts = activeProducts
.Where(p => string.Equals(
p.Brand.Name,
searchTerm.Trim(),
StringComparison.CurrentCultureIgnoreCase))
.Skip(_recordsPerPage * (page - 1))
.Take(_recordsPerPage);
}
}
else
{
// And here.
activeProducts = activeProducts
.Skip(_recordsPerPage * (page - 1))
.Take(_recordsPerPage);
}
从web.config向此recordsPerPage变量传递值的位置。我正在读构造器。我已经调试过了,可以看到我的所有分页属性都应该是这样的,以便将我对LINQ所做的修改分配给新变量?如果愿意,您可以重新分配给
activeProducts
变量。更新了一个例子。
var activeProducts = _context.Products.Where(p => !p.IsDeleted);
if (!string.IsNullOrEmpty(searchTerm))
{
if (searchType == "category")
{
// See the change here?
activeProducts = activeProducts
.Where(p => string.Equals(
p.Category.Name,
searchTerm.Trim(),
StringComparison.CurrentCultureIgnoreCase))
.OrderBy(p => p.Category.Name)
.Skip(_recordsPerPage * (page - 1))
.Take(_recordsPerPage);
}
else
{
// Here.
activeProducts = activeProducts
.Where(p => string.Equals(
p.Brand.Name,
searchTerm.Trim(),
StringComparison.CurrentCultureIgnoreCase))
.Skip(_recordsPerPage * (page - 1))
.Take(_recordsPerPage);
}
}
else
{
// And here.
activeProducts = activeProducts
.Skip(_recordsPerPage * (page - 1))
.Take(_recordsPerPage);
}