【问题标题】:Fill view when passing a param using Linq to EF使用 Linq 向 EF 传递参数时填充视图
【发布时间】:2013-03-09 22:19:36
【问题描述】:

下面的代码正在运行.. 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();
    }
}

我想在函数中添加一个额外的参数以跳过库存搜索

CustomView - 添加 bool

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

当我将 bool 参数添加到 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();
    }
}

我收到以下错误:

无法从用法中推断方法“System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)”的类型参数。尝试明确指定类型参数。

传递参数时如何调用返回填充视图返回 data.Select(CustomView, false).ToList()?

附言获取 ONE 记录(不是 .ToList )时,CustomView 的工作原理是 return CustomView(data, false);

【问题讨论】:

    标签: c# asp.net entity-framework function linq-to-entities


    【解决方案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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-23
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多