【问题标题】:Call SQL Server UDF in LINQ query在 LINQ 查询中调用 SQL Server UDF
【发布时间】:2018-09-30 09:12:33
【问题描述】:

我在 SQL Server 中有这个 UDF:[dbo].[ObtieneEdad]

EDMX 文件中的这个定义:

<Function Name="ObtieneEdad" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="true" ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo" ReturnType="int">
  <Parameter Name="fechaNacimiento" Type="datetime" Mode="In" />
</Function>

类中的这个静态方法:

    [EdmFunction("ControlVisitas3Model.Store", "ObtieneEdad")]
    public static int? ObtieneEdad(DateTime fechaNacimiento)
    {
        throw new NotSupportedException("Direct calls are not supported.");
    }

最后,我尝试在这个查询中使用:

personas = personas.Where(p => !p.PersonaFechaNacimiento.HasValue ? false : DataWare.Persona.ObtieneEdad(p.PersonaFechaNacimiento.Value) >= edadMinima && DataWare.Persona.ObtieneEdad(p.PersonaFechaNacimiento.Value) <= edadMaxima);

其中“角色”是 IQuerable。

运行该查询时,会引发此异常:

LINQ to Entities does not recognize the method 'System.Nullable`1[System.Int32] ObtieneEdad(System.DateTime)' method, and this method cannot be translated into a store expression.

这里可能缺少什么?

我已按照此网页的说明进行操作:

https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/how-to-call-custom-database-functions

【问题讨论】:

  • 它应该可以正常工作。很难说你的错误到底在哪里,因为有很多选项,比如EdmFunction 属性中的错误模型名称,Function xml 节点的错误放置(例如,不在 SSDL 部分内)等等。跨度>

标签: c# entity-framework-6 linq-to-entities user-defined-functions edmx


【解决方案1】:

我是这样解决的:

  • 将此方法添加到上下文类(继承 DbContext):

    [DbFunction("ControlVisitas3Model.Store", "ObtieneEdad")]
    public int ObtieneEdad(DateTime fechaNacimiento)
    {
        throw new NotImplementedException();
    }
    
  • 这样称呼它:

    personas = personas.Where(p => p.PersonaFechaNacimiento.HasValue && db.ObtieneEdad(p.PersonaFechaNacimiento.Value) >= edadMinima && db.ObtieneEdad(p.PersonaFechaNacimiento.Value) <= edadMaxima);
    

问候

詹姆

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2011-04-18
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多