Search code examples
entity-frameworkt-sqlentity-framework-4user-defined-functions

Entity Framework scalar function mapping


I have a scalar function:

CREATE FUNCTION [dbo].[CheckLocation]
(
    @locationId Int
)
RETURNS bit
AS
BEGIN
    //code
END

I want to use it in Entity Framework context.

I have added this in the SSDL of the EDMX file:

<Function Name="CheckLocation" ReturnType="bit" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="true" ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo" >
    <Parameter Name="locationId" Type="int" Mode="In" />
</Function>

I have also created a partial class with a method decorated with EdmFunctionAttribute:

public partial class MainModelContainer
{
    [EdmFunction("MainModel.Store", "CheckLocation")]
    public bool CheckLocation(int locationId)
    {
        throw new NotSupportedException("Direct calls not supported");
    }
}

I try to use this function like this:

Context.CheckLocation(locationId);

And I get NotSupportedException("Direct calls not supported").

It works within the Select method, but it does not suit me.

How can I call this function without using the Select method?


Solution

  • you need to access it as a select

    var students = context.Locations
        .Select ( new  {  location= CheckLocation(locationId)}):