首页 > 解决方案 > ThreadAbortException:系统错误将 Postgres 函数(表返回)的结果读取到 EF 可枚举中

问题描述

我在尝试将 Postgres 函数的结果加载到 EF 实体时遇到以下错误。

错误:

Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over the results of a query for context type 'Rainman.Data.RainmanDbContext'.
System.Threading.ThreadAbortException: System error.
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior)
   at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.FromSqlQueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.FromSqlQueryingEnumerable`1.Enumerator.MoveNext()

运行以下代码时:

    FormattableString query = $"SELECT sortedsetkey as \"SortedSetKey\", keyorder as \"KeyOrder\", value as \"Value\" FROM public.fn_test_lcr_custom({routePlan.DeckApplyCustomer.tg_id}, {routePlan.effective_date});";
    Console.WriteLine($"\n\nQUERY:\n{query}\n\n");
    IEnumerable <CustomerRoutingCache> tmpList = RainmanDbContext.CustomerRoutingCaches.FromSqlInterpolated(query).AsEnumerable();

在 Postgres 端(版本 13)调用的函数的这个 SQL 函数定义:

CREATE OR REPLACE FUNCTION public.fn_test_lcr_custom(
    p_tg_id text,
    p_as_of_date timestamp with time zone)
    RETURNS TABLE(SortedSetKey text, KeyOrder int, Value text) 

它被翻译成的类是:

public class CustomerRoutingCache
{
    [Key]
    public string SortedSetKey { get; set; }
    public int KeyOrder { get; set; }
    public string Value { get; set; }
}

使用 .net 核心 5,npgsql

标签: postgresql.net-coreentity-framework-corenpgsqlpostgresql-13

解决方案


推荐阅读