xx7*_*aBs 6 c# sql-server entity-framework
在我的数据库中,我已经定义了一些函数,让我们说它被称为fnTest.是否可以从我的LINQ/EF查询中调用该函数?像这样的东西:
var param3, param4;
var res = (from x in db.Something
where x.field1 > 0
orderby fnTest(x.f1, x.f2, param3, param4)
select x).Take(20);
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我需要在DB端执行该函数,因为我需要使用它返回的值对数据进行排序.前两个参数是表中的字段,后两个参数是一些将在程序中更改的数字,但对于每个查询将是常量.
有可能以某种方式调用已在DB中创建的函数吗?或者我需要使用这样的东西:
((IObjectContextAdapter) context).ObjectContext.CreateQuery
Run Code Online (Sandbox Code Playgroud)
并手动编写查询?
首先,fnTest必须首先在数据库中创建用户定义的函数:
CREATE FUNCTION [fnTest] (@fi int, @f2 int, @param3 int, @param4 int)
RETURNS int
AS ...
Run Code Online (Sandbox Code Playgroud)
然后在.edmx文件中,声明如下函数:
<Function Name="fnTest" ReturnType="int" Schema="dbo" >
<Parameter Name="f1" Mode="In" Type="int" />
<Parameter Name="f2" Mode="In" Type="int" />
<Parameter Name="param3" Mode="In" Type="int" />
<Parameter Name="param4" Mode="In" Type="int" />
</Function>
Run Code Online (Sandbox Code Playgroud)
现在,您可以将此函数绑定到模型中的方法,如下所示:
[EdmFunction("MyNamespace", "fnTest")]
public static int fnTest(int f1, int f2, int param3, int param4)
{
throw new NotSupportedException("Direct calls are not supported.");
}
Run Code Online (Sandbox Code Playgroud)
您现在可以在标准LINQ查询中使用此方法.
进一步阅读