[英]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.