如何重写一个方法,以便它可以在LINQ to Entities中执行?

时间:2015-03-20 19:32:03

标签: c# linq entity-framework linq-to-entities

我有以下帮助方法:

public static double CalculateKilosPerMeter(double diameter, double thickness)
{
    return (diameter - thickness) * thickness * Math.PI * 0.008;
}

我在为特定实体创建Model类的实例时使用它。

return pt => new ViewablePipeTypeModel()
{
    Id = pt.Id,
    KilosPerMeter = Logic.CalculateKilosPerMeter(pt.Diameter, pt.Thickness)
};

当我执行上面的代码时,我得到以下异常:

 LINQ to Entities does not recognize the method 'Double CalculateKilosPerMeter(Double, Double)' method, and this method cannot be translated into a store expression

所以,我想这是因为EF需要一个ExpressionFunc。

如何转换我的方法,使其在LINQ to Entities下运行?

3 个答案:

答案 0 :(得分:0)

您可以首先获取所有必需数据的匿名类型记录,然后使用AsEnumerable()使用常规LINQ to Objects。

var objs = ... pt => new
{
    Id = pt.Id,
    Diam = pt.Diameter,
    Thick = pt.Thickness
};

var res = objs.AsEnumerable().Select(p => new ViewablePipeTypeModel()
{
    Id = p.Id,
    KilosPerMeter = Logic.CalculateKilosPerMeter(p.Diam, p.Thick)
};

答案 1 :(得分:0)

创建编译查询并将逻辑移动到该查询中。它将生成一个可以在查询中使用的函数,就好像它是一个常规函数一样。

Func<MyDataContext, double, double, double> calculateKilosPerMeter =
    CompiledQuery.Compile((MyDataContext dc, double diameter, double thickness) =>
        (diameter - thickness) * thickness * Math.PI * 0.008
    );
var query =
    from pt in dc.PipeTypes
    where ...
    select new ViewablePipeTypeModel()
    {
        Id = pt.Id,
        KilosPerMeter = calculateKilosPerMeter(dc, pt.Diameter, pt.Thickness),
    };

答案 2 :(得分:-1)

方式:

public Expression<Func<PipeType, double>> KilosPerMeter
{
    return f=>(f.diameter - f.thickness) * f.thickness * Math.PI * 0.008;
}

<强>用法:

public void DoSomething()
{
  using(var vptm = new ViewablePipeTypeModel())
  {
      var qry = from pt in vptm
          select new
          {
            Id = pt.Id,
            KpM = pt.KilosPerMeter()
          };
  }
}

注意:我没有机会测试它。

我建议您阅读这篇文章:Calling Functions in LINQ to Entities Queries