繁体   English   中英

如何从Entity Framework 6(数据库优先)和Npgsql执行存储过程?

[英]How to execute stored procedure from Entity Framework 6 (database first) and Npgsql?

这是错误吗?

我的组件是:

  1. .NET 4.6.1
  2. 实体框架6.0
  3. Npgsql 3.0.5
  4. PostgreSQL 9.5

首先,我在PostgreSQL 9.5中创建了一个表和存储过程

CREATE TABLE hello
(
  msg text
)
WITH (
  OIDS=FALSE
);
ALTER TABLE hello
  OWNER TO postgres;

CREATE OR REPLACE FUNCTION sayhello()
  RETURNS SETOF hello AS
$BODY$ 

select
 *
 from version()

  $BODY$
  LANGUAGE sql VOLATILE
  COST 100
  ROWS 1000;
ALTER FUNCTION sayhello()
  OWNER TO postgres;

第二,我转到.edmx文件(实体框架6.0),选择“从数据库更新”,选择新表“ hello”和新存储过程“ sayhello”。

现在,模型浏览器显示新的表实体和导入的函数。

第三,向WCF文件添加一个新过程:

public string SayHello()
{
            using (var ctx = new chaosEntities())
            {
                var x = ctx.sayhello();
                return "Hello";
            }
}

将WCF服务设置为“启动”项目并启动“调试”。

WCF测试客户端启动。 从WCF服务执行SayHello()会导致:

public virtual ObjectResult<hello> sayhello()
{
    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<hello>("sayhello");
}

执行此操作后,我得到:

EntityFramework.dll中发生类型为'System.Data.Entity.Core.EntityCommandCompilationException'的异常,但未在用户代码中处理

附加信息:在准备命令定义时发生错误。 有关详细信息,请参见内部异常。

内部异常是:{“值不在预期范围内。”}

由于我有数百个存储过程,因此,非常感谢有关如何解决此问题的任何帮助。

TIA

注意:我怀疑问题出在NpgsqlServices.TranslateCommandTree,但我只是在猜测。

我永远无法使它按我希望的方式工作(通过EntityFramework),所以我最终做到了。 我肯定会接受更好的解决方案!

下面的代码直接调用Npgsql来避免整个EntityFramework。

public string SayHello()
        {
            using (var ctx = new chaosEntities())
            {
                var b = ctx.Database.Connection.ConnectionString;

                using (var conn = new Npgsql.NpgsqlConnection(connectionString: b))
                {
                    conn.Open();
                    using (var tran = conn.BeginTransaction())
                    using (var command = conn.CreateCommand())
                    {
                        command.CommandText = "sayhello";
                        command.CommandType = CommandType.StoredProcedure;

                        var g = (string)command.ExecuteScalar();
                        return g;
                    }
                }
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM