c# – 在实体框架中使用存储的函数

前端之家收集整理的这篇文章主要介绍了c# – 在实体框架中使用存储的函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个旧的Oracle数据库,我试图在EntityFramework 4.1应用程序中使用它.
我已经读过oracle与EF有很大的限制 – 你不能用EF调用Oracle存储的函数,除非你创建一个包装过程.

我的数据库中有成千上万的存储函数,有没有其他方法可以解决它?
喜欢使用原始Context.sqlQuery()?

到目前为止,我找不到解决方案……

Oracle docs:

Oracle developers can leverage PL/sql stored @H_502_12@procedures,with limitations,within the entity framework via Entity Framework Function Imports (used to call the procedures explicitly) and stored procedure mappings (which are automatically called for entity Insert,Update,and Delete operations).

@H_502_12@Only Oracle stored procedures can be called by Entity Framework,not stored functions. (Oracle stored functions can be used if they are wrapped inside of a stored procedure that uses an OUT parameter for the stored function return value.)

解决方法

如果您正在使用Entity Framework 4.1 Code First,则可以尝试使用 Database.SqlQuery Method.
例如,对于此功能
CREATE OR REPLACE FUNCTION USERNAME_CTX.FUNCTION1 (param number)
 RETURN number
AS
BEGIN
 return param + 1;
END;

你可以使用这段代码

using (var ctx = new Model()) {
   var result =  ctx.Database.sqlQuery<int>("select username_ctx.FUNCTION1(:p0) from dual",1).FirstOrDefault();

}

编辑:

请注意dotConnect for Oracle的此解决方案(可能对实现类似的ODP.NET解决方案很有用)

对于这个功能

CREATE OR REPLACE FUNCTION USERNAME_CTX.FUNCTION2 (param number,int_param out number,str_param out varchar2)
  RETURN number
AS
BEGIN
   int_param := param + 2;
   str_param := 'value';
   return param + 1;
END;

您可以使用以下代码

using (var ctx = new Model()) {
       var firstParam = new Devart.Data.Oracle.OracleParameter("p0",OracleDbType.Number,1,ParameterDirection.Input);
       var secondParam = new Devart.Data.Oracle.OracleParameter("p1",ParameterDirection.Output);
       var thirdParam = new Devart.Data.Oracle.OracleParameter("p2",OracleDbType.VarChar,ParameterDirection.Output);
       var cursorParam = new Devart.Data.Oracle.OracleParameter("cursor_param",OracleDbType.Cursor,ParameterDirection.Output);

       var result = ctx.Database.sqlQuery<int>(
        @"declare
             res number;  
        begin
             res := username_ctx.FUNCTION2(:p0,:p1,:p2);
             open :cursor_param for select res from dual;
        end;",firstParam,secondParam,thirdParam,cursorParam).FirstOrDefault();

       Console.WriteLine("Return value: {0}; int_param: {1}; str_param: '{2}'",result,secondParam.Value,thirdParam.Value);
      }

编辑2

或使用此代码

using (var ctx = new Model()) {
       var firstParam = new Devart.Data.Oracle.OracleParameter("p0",ParameterDirection.Output);
       var resultParam = new Devart.Data.Oracle.OracleParameter("res",ParameterDirection.Output);
       ctx.Database.ExecutesqlCommand(@"begin  :res := username_ctx.FUNCTION2(:p0,:p2);  end;",resultParam);
       Console.WriteLine("Return value: {0}; int_param: {1}; str_param: '{2}'",resultParam.Value,thirdParam.Value);
 }
原文链接:https://www.f2er.com/csharp/244438.html

猜你在找的C#相关文章