自定义SQL函数和$ C C一(EF 4.1)$自定义、函数、SQL、EF

2023-09-04 08:05:55 作者:夏未央

我用实体框架4.1 RC 和code第一种方法。 我如何可以调用自定义的SQL函数?

如果我使用的 EdmFunction 的属性,我应该指定哪些空间?

  [EdmFunction(命名空间,GetAge)
公共静态INT GetAge(人P)
{
    抛出新NotSupportedException异常(...);
}
 

当我试图用这样的功能如下异常被抛出执行LINQ查询:

  

的类型指定的方法'...'   '...'不能被翻译成LINQ到   实体存储EX pression。

解决方案 C 注册并使用sqlite 自定义函数

如果你想调用SQL函数,你必须执行一个自定义的SQL查询。要做到这一点使用context.Database.SqlQuery。实体框架支持的存储过程映射,但此功能不支持的DbContext的API(EF 4.1)。如果要调用存储过程,你必须再次使用context.Database.SqlQuery。存储过程不能永远在LINQ查询使用。

EdmFunction 是ObjectContext的API和实体设计功能。名称空间被设定为在EDMX文件中定义的命名空间。当使用code-首先你没有EDMX文件,你不能定义函数映射。

顺便说一句。如果按照code第一种方法,你不应该有任何的存储过程或SQL函数,因为你的数据库是由你的模型(code)定义和实体框架生成的。

I'm using Entity Framework 4.1 RC and code first approach. How can I call custom SQL functions?

If I use EdmFunction attribute, what namespace should I specify?

[EdmFunction("Namespace", "GetAge")] 
public static int GetAge(Person p) 
{  
    throw new NotSupportedException(…); 
}

When I try to execute a LINQ query with such function the following exception is thrown:

The specified method '...' on the type '...' cannot be translated into a LINQ to Entities store expression.

解决方案

If you want to call SQL function you must execute a custom SQL query. To do that use context.Database.SqlQuery. Entity framework supports mapping of stored procedures but this feature is not supported in DbContext API (EF 4.1). If you want to call a stored procedure you must again use context.Database.SqlQuery. Stored procedures can't never be used in Linq queries.

EdmFunction is feature of ObjectContext API and Entity designer. The namespace is set to the namespace defined in the EDMX file. When using code-first you don't have the EDMX file and you can't define function mapping.

Btw. if you follow the code first approach you should not have any stored procedures or SQL functions because you database is defined by you model (code) and generated by entity framework.

 
精彩推荐