实体框架核心:用户定义的 SQL 函数

Jer*_*ude 5 entity-framework entity-framework-core

是否可以从 EF Core 中的查询接口调用用户定义的 SQL 函数?例如,生成的 SQL 看起来像

select * from X where dbo.fnCheckThis(X.a, X.B) = 1
Run Code Online (Sandbox Code Playgroud)

就我而言,此子句是对其他 Query() 方法调用的补充,因此 FromSQL() 不是一个选项。

Sha*_*ica 9

我刚刚在这篇文章的帮助下解决了这个问题(H/T @IvanStoev对这个问题的评论)。

在你的DbContext班级:

[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
}
Run Code Online (Sandbox Code Playgroud)

请注意,该函数必须位于DbContext类中,即使它是静态的。

然后创建数据库迁移并在脚本中定义用户函数。

用法:

var query = db.Foos.Where(f => MyDbContext.SatisfiesMyUserFunction(f.FieldValue));
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用 Fluent api 手动注册静态函数,则不需要位于派生的 DbContext 类中。从 EF Core 2.1 开始,它也可以是成员函数,但需要在派生的 DbContext 类上声明。 (2认同)