Entity Framework Core: User Defined SQL Functions

柔情痞子 提交于 2020-05-23 21:10:45

问题


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:


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));


来源:https://stackoverflow.com/questions/50089479/entity-framework-core-user-defined-sql-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!