简体   繁体   English

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

[英]MVC4 pass lambda from controller to repository

I have a controller that calls a method in my repository that runs a linq to entities query to get a list of products for my application. 我有一个控制器,该控制器在我的存储库中调用一个方法,该方法运行linq进行实体查询以获取我的应用程序的产品列表。 I'd like to add the ability for a user to filter the results (something like standard price high to low, low to high, etc etc). 我想为用户增加过滤结果的能力(诸如标准价格从高到低,从低到高等)。

So I'm thinking I need to dynamically populate my orderby in the repository, but am having trouble with this. 因此,我认为我需要在存储库中动态填充orderby,但遇到了麻烦。 I'm shaky on generics in c#, so please bear with me. 我对C#中的泛型不满意,请耐心等待。

Controller 控制者

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

Model 模型

    //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);
                }
            }
      }

So I'm thinking I need to pass a Func<TSource, TKey> from my controller, but I having trouble piecing together how to accomplish that. 所以我想我需要从我的控制器传递一个Func<TSource, TKey> ,但是在拼凑如何实现这一点时遇到了麻烦。 Any help would be greatly appreciated. 任何帮助将不胜感激。

You can do this by passing in a Func<IQueryable<T>, IOrderedQueryable<T>> which in this case would be 您可以通过传入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();
  }
 }

And you could call it like this: 您可以这样称呼它:

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

I'm assuming the struggle is coming in because the ordering element is not always going to be the same type. 我假设斗争即将来临,因为排序元素不一定总是相同的类型。 Rather than overcomplicating a fairly simple choice by passing around a genericized generic, why not just pass in the option and take it into account while building the linq query? 与其通过传递泛型泛型来使一个相当简单的选择复杂化,不如在构建linq查询时不仅仅传递选项并将其考虑在内?

In the code at my workplace we'd probably achieve this with an enum, something like: 在工作场所的代码中,我们可能会使用枚举来实现此目的,例如:

public enum OrderByValue
{
    DateAdded,
    Price,
    OtherChoice
}

Then, your query would just have a decision to make in the middle: 然后,您的查询将只在中间做出决定:

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();

If it is in fact just a binary choice you could also do the same without the enum and the switch, and just pass in a bool. 如果实际上只是二进制选择,您也可以在没有枚举和开关的情况下执行相同的操作,只需传入布尔值即可。

暂无
暂无

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

相关问题 如何将xml从控制器传递到mvc4中的其他控制器 - how to pass xml from controller to other controller in mvc4 如何通过清单 <model> 从控制器在MVC4中查看? - how to pass List<model> to controller from view in MVC4? 如何在mvc4中从控制器传递一对多到视图 - how to pass one-to-many from controller to view in mvc4 无法将JSON对象从Rest Client传递到MVC4控制器C# - Not able to pass JSON object from Rest Client to MVC4 controller C# 如何通过单击编辑按钮在 mvc4 devExpress 中使用 SetDataItemTemplateContent 将参数从 gridview 传递到 controller? - How to pass Parameter from gridview to controller using SetDataItemTemplateContent in mvc4 devExpress by clicking Edit Button? 将数据从视图传递到ASP.NET MVC4剃须刀中的控制器 - Pass data from view to controller in asp.net mvc4 razor 从MVC4中的视图将2个不同的模型传递到控制器的适当方法是什么 - Whats the Appropriate Method to pass 2 different Models to the Controller from a View in MVC4 如何在MVC4中不使用Ajax的情况下将参数从View传递到Controller? 有可能吗? - How to pass parameters from View to Controller without using Ajax in MVC4?Is it possible? 如何将集合从视图传递到ASP.NET MVC4中的控制器 - How to pass collection from view to controller in asp.net MVC4 我如何使用 datapost 将参数从 jqgrid 传递到 controller(使用 MVC4 和 asp.net) - how can i pass parameter from jqgrid to controller with datapost (using MVC4 and asp.net )
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM