How to call DB function from EF LINQ query?

前端 未结 2 1787
予麋鹿
予麋鹿 2020-12-19 06:54

In my database I have define some function, let\'s say it\'s called fnTest. Is it possible to call that function from my LINQ/EF query? Something like this:

相关标签:
2条回答
  • 2020-12-19 07:40

    First off, fnTest will have to be created as a user-defined function in the database first:

    CREATE FUNCTION [fnTest] (@fi int, @f2 int, @param3 int, @param4 int)
    RETURNS int
    AS ...
    

    Then in your .edmx file, declare the function like this:

    <Function Name="fnTest" ReturnType="int" Schema="dbo" >
        <Parameter Name="f1" Mode="In" Type="int" />
        <Parameter Name="f2" Mode="In" Type="int" />
        <Parameter Name="param3" Mode="In" Type="int" />
        <Parameter Name="param4" Mode="In" Type="int" />
    </Function>
    

    Now you can bind this function to a method in your model like this:

    [EdmFunction("MyNamespace", "fnTest")]
    public static int fnTest(int f1, int f2, int param3, int param4)
    {
        throw new NotSupportedException("Direct calls are not supported.");
    }
    

    You can now use this method in standard LINQ queries.

    Further Reading

    • How to: Call Custom Database Functions
    0 讨论(0)
  • 2020-12-19 07:40

    Use sql queries for entities. For exaples look on msdn: http://msdn.microsoft.com/en-us/data/jj592907.aspx

    0 讨论(0)
提交回复
热议问题