8

Is it possible to invoke a user-defined SQL function from the query interface in EF Core? For example, the generated SQL would look like

select * from X where dbo.fnCheckThis(X.a, X.B) = 1

In my case, this clause is in addition to other Query() method calls so FromSQL() is not an option.

1

1 Answer 1

9

I just managed this with help from this article (H/T @IvanStoev for his comment on the question).

In your DbContext class:

[DbFunction("my_user_function_name")]
public static bool SatisfiesMyUserFunction(int i)
{
    throw new Exception(); // this code doesn't get executed; the call is passed through to the database function
}

Note that the function must be in the DbContext class, even though it is static.

Then create a database migration and define the user function in the script.

Usage:

var query = db.Foos.Where(f => MyDbContext.SatisfiesMyUserFunction(f.FieldValue));
Sign up to request clarification or add additional context in comments.

5 Comments

The static function does not need to be in the derived DbContext class if you register it manually with the fluent api. As of EF Core 2.1 it can also be a member function, but then does need to be declared on the derived DbContext class.
@Shaul Behr. Does EF Core 2.1 support mapping Sql Table Valued functions?
@RaidaAdn I don't know; haven't tried. Have you tried?
Yes, I tried yesterday. But after googling lot enough, I concluded that the current possible solution to call the Sql Table Valued functions is to use FromSql() in EFCore.
By putting the function in DbContext, I didn't need to make it static. That means I could do this instead: var query = db.Foos.Where(f => db.SatisfiesMyUserFunction(f.FieldValue));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.