当命令文本包含 DDL 和 DML 指令时,ExecuteSqlCommand 在 Entity Framework 中失败

ExecuteSqlCommand fails in Entity Framework when the command text has a DDL and DML instruction

在 C# 中,使用 NpgSQL 连接到 Postgres 数据库,我试图执行一个具有 DDL 和 DML 指令的独特命令,但是该命令不起作用。

样本:

var m_comandoSQL = @"DROP TABLE IF EXISTS public.test_55;
CREATE TABLE public.test_55 ( ds_nome VARCHAR(50) );
SELECT * FROM public.test_55;";

var m_modelo = new Modelo(); // Modelo is a dbContext
m_modelo.Database.ExecuteSqlCommand(m_comandoSQL);

调用 ExecuteSqlCommand 时,引发以下异常

Npgsql.NpgsqlException (0x80004005): 42P01: relation "public.test_55" does not exist

em Npgsql.NpgsqlConnector.DoReadSingleMessage(DataRowLoadingMode dataRowLoadingMode, Boolean returnNullForAsyncMessage, Boolean isPrependedMessage)

em Npgsql.NpgsqlConnector.ReadSingleMessage(DataRowLoadingMode dataRowLoadingMode, Boolean returnNullForAsyncMessage)

em Npgsql.NpgsqlCommand.Execute(CommandBehavior behavior)

em Npgsql.NpgsqlCommand.ExecuteNonQueryInternal()

em System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed)

em System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)

em System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)

em System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass59.b__57()

em rei_cadastros.InitializeTeste.Main(String[] args)

如果我单独执行命令,不会发生错误。

你可以试试这个:

var m_comandoSQL = @"SET client_min_messages = error;
DROP TABLE IF EXISTS public.test_55;
CREATE TABLE public.test_55 ( ds_nome VARCHAR(50) );
SELECT * FROM public.test_55;";

var m_modelo = new Modelo(); // Modelo is a dbContext
m_modelo.Database.ExecuteSqlCommand(m_comandoSQL);

错误的原因可能是当 table 不存在时由 drop table 语句生成的 postgres 通知。

IF EXISTS

Do not throw an error if the table does not exist. A notice is issued in this case.

正如 Shay Rojansky 提到的,将 NpgSQL 升级到版本 3。2.x 解决了问题