views:

216

answers:

2

I have a user defined function in a SQL Server 2005 database which returns a bit. I would like to call this function via the Entity Framework. I have been searching around and haven't had much luck.

In LINQ to SQL this was obscenely easy, I would just add the function to the Data context Model, and I could call it like this.

bool result = FooContext.UserDefinedFunction(someParameter);

Using the Entity Framework, I have added the function to my Model and it appears under SomeModel.Store\Stored Procedures in the Model Browser.

The model has generated no code for the function, the XML for the .edmx file contains:

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

The closest I could get was something like this:

bool result = ObjectContext.ExecuteFunction<bool>(
    "UserDefinedFunction",
    new ObjectParameter("someParameter", someParameter)
).First();

But I got the following error message:

The FunctionImport 'UserDefinedFunction' could not be found in the container 'FooEntities'.

Names have been changed to protect the innocent.

tldr: How do I call scalar valued user defined functions using Entity Framework 4.0?

A: 

You might find this helpful. It would appear that you can only call them via eSQL directly and not using Linq.

Ben Robinson
I found that article a couple of hours ago, the comments below the article echo my frustration.I have had some success using Entity SQL, although I get a syntax error when I exclude the FROM clause (which is not required for scalar functions).
Evil Pigeon
A: 

I have finally worked it out :D For scalar functions you can append the FROM {1} clause.

bool result = FooContext.CreateQuery<bool>(
    "SELECT VALUE FooModel.Store.UserDefinedFunction(@someParameter) FROM {1}",
    new ObjectParameter("someParameter", someParameter)
).First();

This is definitely a case for using LINQ to SQL over EF.

Evil Pigeon