How to call Scalar-valued function from LINQ to Entities server-side

前端 未结 2 444
无人及你
无人及你 2020-12-31 17:36

I have a Scalar-valued function in my DB:

ALTER FUNCTION [dbo].[fx_fooFunct]
  (@MyParam varchar(max))
RETURNS varchar(max)
AS
BEGIN
  return @MyParam
END


        
相关标签:
2条回答
  • 2020-12-31 17:58

    Well, you need to modify SQL to convert the single/scalar value to table valued function then it will work. As there is no support for scalar valued function yet https://social.msdn.microsoft.com/Forums/en-US/756865e5-ff25-4f5f-aad8-fed9d741c05d/add-scalar-function-to-function-import-folder-in-model-browser-of-entity-framework-40-edmx?forum=adodotnetentityframework

    Scalar function as it was, which doesn't work

    CREATE FUNCTION [dbo].[GetSha256]
    (
        -- Add the parameters for the function here
        @str nvarchar(max)
    )
    RETURNS VARBINARY(32)
    AS
    BEGIN
        RETURN ( SELECT * FROM HASHBYTES('SHA2_256', @str) AS HASH256 );
    END -- this doesn't work.
    

    Scalar function -> Converted to Table Valued function , it works

    CREATE FUNCTION [dbo].[GetSha2561]
    (
        -- Add the parameters for the function here
        @str nvarchar(max)
    )
    RETURNS  @returnList TABLE (CODE varbinary(32))
    AS
    BEGIN
    
        INSERT INTO @returnList
        SELECT HASHBYTES('SHA2_256', @str);
    
        RETURN; -- This one works like a charm.
    
    END
    
    0 讨论(0)
  • 2020-12-31 18:19

    Do you have your function mapped in EDMX? I guess you don't.

    Run Update from database wizard in the designer and under stored procedures select your SQL function to import and follow this article to create helper method marked with EdmFunctionAttribute to expose the SQL function for LINQ-TO-Entities.

    Note: SQL functions are not supported in code-first / fluent-API. You need to use mapping with EDMX.

    ExecuteFunction is used to call features mapped in EDMX - it expects name of the mapped feature (function imports of stored procedures). MSDN says that it can also call mapped functions but I don't know how - it calls function import and SQL function import doesn't have any.

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