繁体   English   中英

MVC4将Lambda从控制器传递到存储库

[英]MVC4 pass lambda from controller to repository

我有一个控制器,该控制器在我的存储库中调用一个方法,该方法运行linq进行实体查询以获取我的应用程序的产品列表。 我想为用户增加过滤结果的能力(诸如标准价格从高到低,从低到高等)。

因此,我认为我需要在存储库中动态填充orderby,但遇到了麻烦。 我对C#中的泛型不满意,请耐心等待。

控制者

model.Products = ProdRepo.GetProducts ((int)CategoryId, 0, 8);

模型

    //get a list of the products
    public List<ProductModel> GetProducts (int CategoryId, int Start, int End) 
    {
        List<ProductModel> Products = new List<ProductModel>();
        var products = (from p in db.products select p).AsEnumerable().OrderByWithDirection(x=> x.date_added, true).Where( x => x.category_id == CategoryId).Where((row, index) => index >= Start && index < End).ToList();
            if (products.Count > 0)
            {
                foreach (var item in products)
                {
                    ProductModel model = new ProductModel();
                    model.CategoryId = item.category_id;
                    model.Description = item.description;
                    model.Id = item.id;
                    model.Product = item.product1;
                    model.DateAdded = item.date_added;
                    model.Image = item.image;
                    model.Price = item.price;

                    Products.Add(model);
                }
            }
      }

所以我想我需要从我的控制器传递一个Func<TSource, TKey> ,但是在拼凑如何实现这一点时遇到了麻烦。 任何帮助将不胜感激。

您可以通过传入Func<IQueryable<T>, IOrderedQueryable<T>>来实现此目的。

 public List<ProductModel> GetProducts (int CategoryId, int Start, int End, Func<IQueryable<ProductModel>, IOrderedQueryable<ProductModel>> order? = null)
 {
  //code shown in question

  if( order != null )
  {
   Products = order(Products).ToList();
  }
 }

您可以这样称呼它:

model.Products = ProdRepo.GetProducts ((int)CategoryId, 0, 8, order: q => q.OrderBy(prod => prod.SomeField));

我假设斗争即将来临,因为排序元素不一定总是相同的类型。 与其通过传递泛型泛型来使一个相当简单的选择复杂化,不如在构建linq查询时不仅仅传递选项并将其考虑在内?

在工作场所的代码中,我们可能会使用枚举来实现此目的,例如:

public enum OrderByValue
{
    DateAdded,
    Price,
    OtherChoice
}

然后,您的查询将只在中间做出决定:

var products = (from p in db.products select p).AsEnumerable();
switch(orderByValue)
{
    case OrderByValue.DateAdded:
    products = products.OrderByWithDirection(x=> x.date_added, true);
    break;

    case OtherStuff:
    ...
}
products = products.Where( x => x.category_id == CategoryId)
    .Where((row, index) => index >= Start && index < End)
    .ToList();

如果实际上只是二进制选择,您也可以在没有枚举和开关的情况下执行相同的操作,只需传入布尔值即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM