2013-03-09 12 views
1

下面的代碼正在工作.. CustomView填充時沒有任何錯誤。使用Linq將參數傳遞給EF時填充視圖

CustomView

public static ProductView CustomView(Product data) 
{ 
    var view = new ProductView(); 
    view.ID = data.ID; 
    view.Number = data.Number; 

    var invetoryCount = GetInvetoryCountNumber(data.Number); 
    if (invetoryCount < 1) 
     view.SoldOut = true; 

    return view; 
} 

功能

public static List<ProductView> GetAll() 
{ 
    using (var ctx = new DBSolutionEntities()) 
    { 
     var data = ctx.Products.OrderBy(p => p.Name).ToList(); 
     return data.Select(CustomView).ToList(); 
    } 
} 

我想額外PARAM添加到功能跳過庫存搜索

CustomView - 添加布爾

public static ProductView CustomView(Product data, bool skipInvCheck) 
{ 
    var view = new ProductView(); 
    view.ID = data.ID; 
    view.Number = data.Number; 

    if(skipInvCheck) 
    { 
     var invetoryCount = GetInvetoryCountNumber(data.Number); 
     if (invetoryCount < 1) 
      view.SoldOut = true; 
    }  

    return view; 
} 

當我添加布爾參數去CustomView並調用它

public static List<ProductView> GetWithoutInvSoldOut() 
{ 
    using (var ctx = new DBSolutionEntities()) 
    { 
     var data = ctx.Products.OrderBy(p => p.Name).ToList(); 
     return data.Select(CustomView, false).ToList(); 
    } 
} 

我收到以下錯誤:

The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

我如何可以調用返回填充視圖返回data.Select (CustomView,false).ToList()傳遞參數時?

p.s.當獲得ONE記錄(不是.ToList)時,CustomView的作用爲 返回CustomView(data,false);

回答

1

這裏的主要問題是Select方法需要一個只帶一個參數的函數,但CustomView需要兩個參數。解決這個問題的最簡單方法是通過使用lambda表達式將curry參數bool參數寫入CustomView方法。

public static List<ProductView> GetWithoutInvSoldOut() 
{ 
    using (var ctx = new DBSolutionEntities()) 
    { 
     var data = ctx.Products.OrderBy(p => p.Name).ToList(); 
     return data.Select(x => CustomView(x, false)).ToList(); 
    } 
}