Custom SQL functions and Code First (EF 4.1)

不打扰是莪最后的温柔 提交于 2019-12-23 07:49:19

问题


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.


回答1:


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.




回答2:


As of EF 6.1 it's now possible to map functions, because now it's possiblw to acces the EDM from Code First.

Here is a sample of an implementation that allows to map TVFs and Stored Procedures, but with some limitations. It also uses EF 6 custom conventions.

Hopefully there will be soon more complete solutions:

https://codefirstfunctions.codeplex.com/

NOTE: you can use git to copy the code to your machine and modify/improve it




回答3:


I success this see this project https://github.com/divega/UdfCodeFirstSample



来源:https://stackoverflow.com/questions/5526422/custom-sql-functions-and-code-first-ef-4-1

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