【发布时间】:2020-05-16 12:50:03
【问题描述】:
是否可以从 EF Core 的查询接口调用用户定义的 SQL 函数?例如,生成的 SQL 看起来像
select * from X where dbo.fnCheckThis(X.a, X.B) = 1
就我而言,此子句是对其他 Query() 方法调用的补充,因此 FromSQL() 不是一个选项。
【问题讨论】:
标签: entity-framework entity-framework-core
是否可以从 EF Core 的查询接口调用用户定义的 SQL 函数?例如,生成的 SQL 看起来像
select * from X where dbo.fnCheckThis(X.a, X.B) = 1
就我而言,此子句是对其他 Query() 方法调用的补充,因此 FromSQL() 不是一个选项。
【问题讨论】:
标签: entity-framework entity-framework-core
我刚刚在 this article 的帮助下解决了这个问题(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
}
注意函数必须在DbContext类中,即使它是静态的。
然后创建一个数据库迁移并在脚本中定义用户函数。
用法:
var query = db.Foos.Where(f => MyDbContext.SatisfiesMyUserFunction(f.FieldValue));
【讨论】:
DbContext,我不需要将其设为静态。这意味着我可以这样做:var query = db.Foos.Where(f => db.SatisfiesMyUserFunction(f.FieldValue));