在实体框架处检查空参数

时间:2015-04-07 10:10:48

标签: asp.net-mvc entity-framework

我想让一个查询可以检查参数是否为null以确认操作,看看这个方法来理解我的意思:

private List<CE_ProductBoxViewModel> GetProductList(bool? isDeal, int? catId, int? brandId, int? takeNum)
        {
            List<CE_ProductsLoc> moduleItems = db.CE_ProductsLoc
                .Include(x => x.CE_Products)
                .Include(x => x.CE_Products.CE_ProductsImages)
                .Include(x => x.CE_Products.CE_ProductsRates)
                .Where(x => x.CE_Products.TypeId == 12
                    && x.LanguageId == LangId
                    if(isDeal != null){&& x.CE_Products.IsDeal == isDeal})
                .Take(takeNum ?? int.MaxValue)
                .OrderByDescending(x => x.CE_Products.NumOrder)
                .ThenByDescending(x => x.ProductId).ToList();
        }

我知道它不正确,但我想检查参数是否为null,不要在where子句

中允许它

2 个答案:

答案 0 :(得分:0)

你可以像这样处理你的可查询:

 //here var was an OrderedQueryable because order was the last clause
 IQueryable<CE_ProductsLoc> moduleItems = db.CE_ProductsLoc
                .Include(x => x.CE_Products)
                .Include(x => x.CE_Products.CE_ProductsImages)
                .Include(x => x.CE_Products.CE_ProductsRates)
                 .Where(x => x.CE_Products.TypeId == 12
                    && x.LanguageId == LangId)
                .OrderByDescending(x => x.CE_Products.NumOrder)
                .ThenByDescending(x => x.ProductId);
 if(isDeal != null){
 moduleItems = moduleItems.Where(x =>x.CE_Products.IsDeal == isDeal);
 }
//executed only here
 List<CE_ProductsLoc> list = moduleItems.Take(takeNum ?? int.MaxValue).ToList();

答案 1 :(得分:0)

根据@Emmanuel M.的谈话,我认为这是最佳表现的正确答案,如果有人有其他答案,请与我们分享

private List<CE_ProductBoxViewModel> GetProductList(bool? isDeal, int? catId, int? brandId, int? takeNum)
        {
            var items = db.CE_ProductsLoc
                .Include(x => x.CE_Products)
                .Include(x => x.CE_Products.CE_ProductsImages)
                .Include(x => x.CE_Products.CE_ProductsRates)
                .Where(x => x.CE_Products.TypeId == 12
                    && x.LanguageId == LangId
                    && x.CE_Products.IsActive == true)
                .Take(takeNum ?? int.MaxValue);
            if (isDeal != null)
                items = items.Where(x => x.CE_Products.IsDeal == isDeal);
            if (catId != null)
                items = items.Where(x => x.CE_Products.CatId == catId);
            if (brandId != null)
                items = items.Where(x => x.CE_Products.BrandId == brandId);
            List<CE_ProductsLoc> moduleItems = items.OrderByDescending(x => x.CE_Products.NumOrder).ThenByDescending(x => x.ProductId).ToList();
        }